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日

悬赏问题

  • ¥60 二次元手游日常任务自动化代肝(相关搜索:自动化)
  • ¥15 mysql将查询的结果作为动态列名怎么实现
  • ¥50 python自动地图截图脚本
  • ¥15 悬赏一本书(内含Matlab代码)的书名、作者
  • ¥20 瑞萨RA4M1芯片刷写为arduino r4 minima
  • ¥15 fastreport怎么判断当前页数
  • ¥15 Kylin-Desktop-V10-GFB-Release-JICAI_02- 2207-Build14-ARM64.iso有没有这个版本的系统啊
  • ¥15 能不能通过蓝牙将传感器数据传送到手机上
  • ¥20 100元python和数据科学实验项目
  • ¥15 根据时间在调用出列表