簡體   English   中英

Axios 錯誤 401(未經授權)嘗試獲取 api 時出錯

[英]Axios Error 401 (Unauthorized) Error when trying to fetch api

  • 錯誤:請求失敗,狀態碼為 401
  • 在 createError (createError.js:16) -at 解決 (settle.js:17)
  • 在 XMLHttpRequest.handleLoad (xhr.js:62)
import React, { Component } from 'react'
import axios from 'axios';
class QuestionAPI extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      MYTOKEN: "cqondiodwoidndndjjajajejh.ndoqndnodnqodoqdiapoe89wnwjwmalmqql2mkKKMkmwk"
    };
  }
  componentDidMount = (MYTOKEN) => {
    axios.get(`http://192.168.0.10:9000/getquestions`,{
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        "token": 'Bearer' + MYTOKEN
      },
    })
      .then(res => {
        console.log("res" + res)
      })
      .catch(e => console.log(e))
  }
  render() {
    return (
      <div>
      </div>
    );
  };
}
export default QuestionAPI;

您的代碼存在一些問題。

  • componentDidMount方法沒有收到任何 arguments。 因此,您必須從localStorage獲取令牌(假設您將令牌存儲在其中)。 您應該從組件 state 中刪除硬編碼令牌。

  • 令牌應該在Authorization header 中發送(您的代碼在token中發送它,這就是 API 發送401 Unauthorized響應的原因)。 並且Bearer旁邊應該有一個空格。

Authorization: `Bearer ${token}`
componentDidMount = () => {
  const token = localStorage.getItem('token') // Replace token with the right key
  if (!token) {
    // handle no token case
    return
  }

  axios.get(`${process.env.API_BASE_URL}/getquestions`, {
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: `Bearer ${token}`,
    },
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM