问题描述
限时送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:关键词]
发布评论