我已经制作了一个类组件令牌并在App.js中导入 在App.js中,有api带有带有授权密钥(即令牌)的标头
到目前为止,我已经尝试过此代码
import React, {Component} from 'react';
import Token from './Token';
class App extends Component {
constructor(){
super();
this.state = { sliders: '', auth_key: ''};
}
componentWillMount(){
this.setState({
auth_key: <Token />
});
}
componentDidMount = () => {
//POST json
var dataToSend = { userid: '223' };
//POST request
fetch('API/PATH', {
method: 'POST', //Request Type
body: dataToSend, //post body
headers: {
'Content-Type': 'application/json',
'Authorization': this.state.auth_key
},
})
.then(response => response.json())
.then(responseJson => {
this.setState({ sliders: responseJson });
alert(JSON.stringify(responseJson));
})
.catch(error => {
console.error(error);
});
}
render(){
return this.state.sliders;
}
}
export default App;
授权中的this.state.auth_key不起作用。请帮忙解决这个问题。
令牌组件类,令牌从令牌类传递到每个组件
import {Component} from "react";
export default class Token extends Component{
constructor(){
super();
this.state = {tokenid: ''};
}
componentDidMount = () => {
let formBody = { usertoken: '223' };
fetch('API/PATH', {
method: 'POST',
body: formBody,
})
.then(response => response.json())
.then(responseJson => {
this.setState({
'tokenid' : responseJson.authtoken
})
})
.catch(error => {
console.error(error);
this.setState({
'tokenid' : ''
})
});
}
render(){
return this.state.tokenid;
}
}