本文介绍了"Access-Control-Allow-Origin"标头的值"http://localhost:4200"不等于所提供的来源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(标题中错误消息的继续)"Origin' http://127.0.0.1:4200 '是因此不允许访问."

(continuation of error message in title) " Origin 'http://127.0.0.1:4200' is therefore not allowed access."

使用相同的API时,我无法在两个不同的域上运行相同的Angular 5网站.

I am unable to run the same Angular 5 site on two different domains when working with the same API.

此错误消息来自Chrome. Firefox中的错误是:

This error message is coming from Chrome. The error in Firefox is:

跨域请求被阻止:相同来源策略"不允许读取 http://上的远程资源myapitest.local/v1/subscription/current/products . (原因:CORS标头"Access-Control-Allow-Origin"与" http://127.0.0.1:4200')

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myapitest.local/v1/subscription/current/products. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘http://127.0.0.1:4200’)

我在使用白色标签版本的Angular应用程序时注意到了这一点,该版本将在常规应用程序的替代URL上运行,但仍使用在相同URL上运行的相同Laravel api.我已经在Laravel中添加了适当的CORS配置,这似乎是浏览器问题-不知道如何解决.

I noticed this when working on a white-labeled version of our Angular app that will be running on an alternative URL from our regular app, but still using the same Laravel api running on the same URL. I've added the appropriate CORS configuration to Laravel, this appears to be a browser issue - not sure how to get around it.

我已经通过将localhost:4200更改为例如127.0.0.1:4200在localhost上重新创建了它.

I have recreated this at localhost by changing from localhost:4200 to 127.0.0.1:4200 for instance.

奇怪的是,使用正确的CORS标头可以进行预检.

Oddly, the preflight seems to be successful with correct CORS headers.

但是,在GET上,响应似乎带有WRONG Access-Control-Allow-Origin标头.

However, on the GET, it seems to come back with the WRONG Access-Control-Allow-Origin header on the response.

在此处值得注意的是,将我的API中的允许的起源"更改为允许所有('*')不能解决此问题.

Worth noting here that changing my Allowed Origins in the API to allow all ('*') does not fix this issue.

我不确定我可以提供什么其他信息或代码来使这一点更加清楚.谢谢.

I'm not sure what other information or code I could provide to make this clearer. Thanks.

推荐答案

让我们假设您的api在8080上运行,而角度代码在4200上.

Let's assume your api runs on 8080 and your angular code on 4200.

在您的应用程序中创建一个名为proxy.conf.json的文件

In your angular app create a file called proxy.conf.json

{
    "/api/": {
        "target": "http://localhost:8080/",
        "secure": false,
        "changeOrigin": true
    }
}

使用此命令启动角度应用程序

Start angular app using this command

ng serve --port 4200 --proxy-config proxy.conf.json

使用此配置,当您调用localhost:4200/api时,它将调用8080,并且不会出现任何CORS错误

With this configuration when you call localhost:4200/api you it will call 8080 and it won't have any CORS error

这篇关于"Access-Control-Allow-Origin"标头的值"http://localhost:4200"不等于所提供的来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 22:37