Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - The 'Access-Control-Allow-Origin' header has a value 'http://localhost:4200' that is not equal to the supplied origin

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

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

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

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’)

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.

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

Oddly, the preflight seems to be successful with correct CORS headers. enter image description here

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...