我正在使用 MERN 堆栈开发一个应用程序,使用 ReactJS 作为前端,使用 NodeJS 作为后端。我已经开发了后端代码并使用邮递员进行了测试,但是在前端访问登录和其他 API 时,它给了我以下错误:
这是我使用axios的前端API访问函数:
try {
const { data } = await axios.post(
`${server}/users/login`,
{
email,
password
},
{
headers: {
"Content-Type": "application/json"
},
withCredentials: true,
}
).then( (response) => {
console.log(response);
})
.catch( (error) => {
console.log("Axios Error: " + error.message);
});
console.log("Login Successfull!");
// toast.success(data.message);
ctx.setIsAuthenticated(true);
ctx.setIsLoading(false);
} catch (error) {
console.log("Login Error: " + error);
// toast.error(error.response.data.message);
ctx.setIsAuthenticated(false);
ctx.setIsLoading(false);
}
我的项目的github链接:https://github.com/shubham-sapkal/DreamSponsor
我尝试过cors到后端服务器:
app.use(cors({
origin: process.env.FRONTEND_URL,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true
}));
事情保持不变。我已经使用邮递员检查了我的整个后端,它工作正常。
我相信sideshowbarker在这里的答案包含解决此问题所需的所有信息。如果您的问题只是您收到的响应中没有“Access-Control-Allow-Origin”标头,您可以设置 CORS 代理来解决此问题。在链接的答案中了解更多信息