You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用登录接口后无法从fetch响应中获取JWT Web Token如何解决

问题原因

fetch API 返回的 Response 实例本身没有 data 属性,你必须先调用异步方法 .json() 解析响应体内容为 JavaScript 对象,才能读取后端返回的 token 字段。同时 fetch 仅在网络层面请求失败时才会进入 catch 块,HTTP 4xx/5xx 状态码不会触发 catch 抛出异常,你也没有做对应的错误处理和 localStorage 存储逻辑。

修正后的代码
async executeLogin (payload) {
  try {
    const response = await fetch('http://localhost:3030/authentication', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })
    // 先解析响应体为JSON格式
    const resData = await response.json()
    if (response.ok) {
      // 读取token并存入localStorage
      const token = resData.token
      localStorage.setItem('jwt_token', token)
      console.log(token)
      alert('You logged in')
      this.$store.commit('setAuthentication', true)
      this.$router.replace({ name: 'Main' })
    } else {
      // 处理接口返回的业务错误,比如账号密码错误等
      alert(`登录失败:${resData.message || '未知错误'}`)
    }
    this.$refs.form.reset()
  } catch (err) {
    console.error('请求错误:', err)
    alert('Something went wrong...')
  }
}
额外说明
  • 如果后端返回的响应体结构不是{token: 'xxx'},你需要根据实际接口返回的字段调整取值逻辑,可在解析完resData后打印该对象确认结构
  • 后续请求需要携带JWT时,直接从localStorage读取即可:localStorage.getItem('jwt_token')

内容的提问来源于stack exchange,提问作者Goose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:57:02