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;
答案 0 :(得分:2)
您的代码存在一些问题。
componentDidMount
方法不接收任何参数。因此,您必须从 localStorage
获取令牌(假设您将令牌存储在其中)。您应该从组件状态中删除硬编码的令牌。
令牌应在 Authorization
标头中发送(您的代码在 token
中发送它,这就是 API 发送 401 Unauthorized
响应的原因)。并且 Bearer
旁边应该有一个空格。
Authorization: `Bearer ${token}`
REACT_APP_
to .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}`,
},
})
}