从源“http://localhost:5173”访问“...”处的 XMLHttpRequest 已被 CORS 策略阻止

问题描述 投票:0回答:1

我正在使用 MERN 堆栈开发一个应用程序,使用 ReactJS 作为前端,使用 NodeJS 作为后端。我已经开发了后端代码并使用邮递员进行了测试,但是在前端访问登录和其他 API 时,它给了我以下错误:

enter image description here

这是我使用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
}));

事情保持不变。我已经使用邮递员检查了我的整个后端,它工作正常。

reactjs node.js cors xmlhttprequest
1个回答
-1
投票

我相信sideshowbarker在这里的答案包含解决此问题所需的所有信息。如果您的问题只是您收到的响应中没有“Access-Control-Allow-Origin”标头,您可以设置 CORS 代理来解决此问题。在链接的答案中了解更多信息

© www.soinside.com 2019 - 2024. All rights reserved.