对 XMLHttpRequest 的访问已被 CORS 政策阻止

编程入门 行业动态 更新时间:2024-10-23 12:33:43
本文介绍了对 XMLHttpRequest 的访问已被 CORS 政策阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

当我尝试在 angular 7 Web 应用程序中执行 PATCH 请求时遇到问题.在我的后端,我有:

I've a problem when I try to do PATCH request in an angular 7 web application. In my backend I have:

app.use((req, res, next) => {
    res.set({
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "*",
        "Access-Control-Allow-Headers": "'Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'",
    });

    next();
});

在我的前端服务中,我:

In my frontend service, I've:

  patchEntity(ent: any, id) {
    let headers = new Headers({ 'Content-Type': '*' });
    let options = new RequestOptions({ headers: headers });
    return this.http.patch('my_url', ent).map((res: Response) => res.json());
  };

错误是:

Access to XMLHttpRequest at 'my_url' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我该怎么办?谢谢.

推荐答案

有两种方法可以解决这个问题:

There are two ways this can be handled:

临时前端解决方案,以便您可以测试 API 集成是否有效:

点击窗口 -> 输入 run 并回车 -> 在命令窗口复制:

Click on window -> type run and hit enter -> in the command window copy:

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

这将打开一个新的Chrome"窗口,您可以在其中轻松工作.这是一个临时解决方案.每次您都必须使用此镀铬窗口.

This will open a new "Chrome" window where you can work easily. This is a temporary solution. Every time you will have to work with this chrome window.

永久解决方案:

在后端代码中,开发者需要在CRUD api调用方法的正上方添加注解@Crossorigin.

In the backend code, the developer needs to add an annotation @Crossorigin right above the CRUD api call method.

让我知道它是否有效.

这篇关于对 XMLHttpRequest 的访问已被 CORS 政策阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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