我已经有了这个发送来自Axios的请求的函数,
export const http = axios.create({
baseURL: 'https://someurl/api',
headers: {
'Content-type': 'application/json',
Accept: 'application/json',
},
});
因此,我可以在应用程序中的任何位置调用此方法,
import {http} from 'src/helpers/HttpHelper';
http
.post(
'/users',
{name: 'mishen'},
)
.then(res => console.log(res))
.catch(error => console.log());
由于也有需要承载令牌的受保护的路由,我try 在我的组件中执行类似的操作,
import {useContext} from 'react';
import {http} from 'src/helpers/HttpHelper';
const MyComponent = () => {
const {userToken} = useContext(AuthContext);
const signUpUser = () => {
http
.post(
'/app_user_role_selection',
{name: 'mishen'},
{headers: {Authorization: `Bearer ${userToken}`}}
)
.then(res => console.log(res))
.catch(error => console.log());
}
...
}
然而,这并不管用.