[英]git api returning 401 unauthorized error when doing axios call but curl returns 200
[英]Axios Error 401 (Unauthorized) Error when trying to fetch api
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}`
REACT_APP_
的環境變量添加到.env
或者如果您有自定義 Webpack 設置,則可以使用dotenv-webpack 。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.