jenhaoyang 2022-07-21 20:51 采纳率: 0%
浏览 20

Fetch的javescript問題

fetch(baseURL + '/api/v1/login', {
    method: 'POST', 
    body: JSON.stringify(body), 
    headers: new Headers({
        'Content-Type': 'application/json'
    })
}).then(function (res) {
    return res.json()          
}).then(function (response) {
    console.log(response.token)
    return response.token
})
//上面是登入後取得token
fetch(baseURL + '/api/v1/user/info', {
    method: 'GET',
    headers: {
        'Authorization': `Bearer ${token}`
    },
}).then(function (response) {
    console.log(response)
})
//下面是需要token才能取得網站資料

想請問上面已經可以console.log跑出token了
那要怎麼把token放進去下面的fetch呢?
感謝!

  • 写回答

1条回答 默认 最新

  • 林地宁宁 2022-07-22 02:01
    关注

    把 promise 链串起来:

    fetch(baseURL + '/api/v1/login', {
        method: 'POST', 
        body: JSON.stringify(body), 
        headers: new Headers({
            'Content-Type': 'application/json'
        })
    }).then(function (res) {
        return res.json()          
    }).then(function (response) {
        console.log(response.token)
        return response.token
    }).then(function (token) {
      return fetch(baseURL + '/api/v1/user/info', {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${token}`
        },
      })
    }).then(function (response) {
      console.log(response)
    })
    
    评论

报告相同问题?

问题事件

  • 创建了问题 7月21日