我正在开发一个以 NodeJs 作为后端的 Web 应用程序的 React 部分。我在登录操作后传递授权时遇到问题。当用户登录时,会生成一个 token ,我将这个 token 保存在本地存储中。然后我用它来控制网站上的用户,代码如下:
const PrivateRoute = ({component: Component, ...rest}) =>(
<Route {...rest} render={(props) => (
window.localStorage.token !== undefined
? <Component {...props} />
: <Redirect to="/" />
)} />
现在效果很好,但是当我尝试向服务器发出发布请求时,出现以下错误:
{ type: "ValidationError", details: "Authorization token not passed"}
details: "Authorization token not passed" type:"ValidationError"
我做了一些谷歌搜索,我认为发生错误是因为我没有为应用程序设置 header 对象。但我可能是错的。
如果您能帮助我解决此问题,我将不胜感激。谢谢
最佳答案
axios 和 fetch 一样,可以接受第二个带有 config 的参数,其中一部分可以是 auth token,所以,你可以传入这样的东西:
axios.get(url, {
headers: {
authorization: `Bearer ${auth_token}`
other_header1: 'value',
other_header2: 'value2'
}
}
或者,在获取 token 后,您可以将其设置为默认值,在 axios docs 中查找“配置默认值” .
关于javascript - 如何在 React 应用程序中传递授权 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51063571/