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

编程入门 行业动态 更新时间:2024-09-25 18:34:50

从源“http://localhost:5173”访问“...”处的 XMLHttpRequest <a href=https://www.elefans.com/category/jswz/34/1771151.html style=已被 CORS 策略阻止"/>

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

我正在使用 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链接:

我尝试过cors到后端服务器:

app.use(cors({
    origin: process.env.FRONTEND_URL,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    credentials: true
}));

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

回答如下:

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

更多推荐

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

本文发布于:2024-06-16 07:20:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:已被   策略   localhost   http   CORS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!