[英]Can`t find JSON Web Token from headers
I have set up JWT to be set in localstorage whenever someone logins or registers.我已经将 JWT 设置为在有人登录或注册时设置在本地存储中。 And it works, I can see the token in localstorage.
它有效,我可以在本地存储中看到令牌。 But when I set the token in the headers with axios, node.js in the backend can`t find the token.
但是当我用 axios, node.js 在标头中设置令牌时,后端找不到令牌。 Like it does not exists.
就像它不存在一样。 I have checked it in the front end, I get logs of the token in the headers.
我已经在前端检查了它,我在标题中获得了令牌的日志。 And also when I request from postman it works.
而且,当我向 postman 提出请求时,它也可以工作。 Here is the code.
这是代码。
setAuthToken function = {
const instance = axios.create({
baseURL: "https://localhost:5000",
});
if (token) {
instance.defaults.headers.common["x-auth-token"] = `${token}`;
console.log(instance.defaults.headers.common["x-auth-token"]);
} else {
delete instance.defaults.headers.common["x-auth-token"];
}
}
const loadUser = async () => {
if (localStorage.token) setAuthToken(localStorage.token);
console.log(localStorage.token);
try {
const res = await axios.get("/api/users");
console.log(res);
dispatch({ type: USER_LOADED, payload: res.data });
} catch (err) {
console.log(err.response.data.msg);
dispatch({ type: AUTH_ERROR });
}
The request comes to the await axios statement and goes to catch so error is in the request.请求到达 await axios 语句并去捕获,因此请求中出现错误。
Here is the backend code这是后端代码
// Get current user
router.get("/", auth, async (req, res) => {
try {
const user = await User.findById(req.user.id);
res.status(200).json({ user });
} catch (err) {
console.log(err);
res.status(500).json({ msg: `Server Error` });
}
});
auth middleware function here = {
const token = req.headers["x-auth-token"];
console.log(token, "token in auth.js");
console.log(req.headers, "req.header");
if (!token) {
return res.status(401).json({ msg: `Access denied.` });
}
try {
const decoded = jwt.verify(token, config.get("jwtSecret"));
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({ msg: `Token is not valid` });
}
}
I`m new to backend develoment and axios.我是后端开发和 axios 的新手。 Can someone help me please.
有人能帮助我吗。 Thank you Here are the console.logs
谢谢 这里是console.logs
Little update, it looks like there is a problem with proxy, I am using my own backend api, and also movie data base api.小更新,代理好像有问题,我用的是我自己的后端api,还有电影数据库api。 So maybe thats why I cant set headers?
所以也许这就是为什么我不能设置标题? Here are new logs:
以下是新日志:
config: Object { url: "/api/users", method: "get", timeout: 0, … }
data: "Proxy error: Could not proxy request /api/users from localhost:3000 to http://localhost:5000/ (ECONNREFUSED)."
headers: Object { connection: "keep-alive", date: "Wed, 05 May 2021 13:18:05 GMT", "keep-alive": "timeout=5", … }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 500
statusText: "Internal Server Error
I think the issue is because you are setting you are setting up your instance wrongly set up your instance in a new file config.js
-我认为问题是因为您正在设置您正在设置您的实例错误地在一个新文件
config.js
中设置您的实例 -
import Axios from 'axios';
const baseURL = "http://localhost:5000";
const axiosInstance = Axios.create({
baseURL: baseURL,
});
axiosInstance.interceptors.request.use(
function (config) {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
export default axiosInstance;
now when making any api request instead of using axios
use axiosInstance
eg-现在在发出任何 api 请求而不是使用
axios
时使用axiosInstance
axiosInstance.get('/something').then(res => console.log(res)).catch(err => console.log(err))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.