No Access-Control-Allow-Origin for angular-cli “lo

2019-05-23 10:47发布

I have a problem related to CORS and the needed headers.

Setup I run a angular project und angular-cli (localhost:4200) I want to access a via a HTTP-Request a JSON from a WebService. When I using the URL direct in the browser everything is fine and the JSON gets displayed. As soon as I send the request from my angular-app I get the following error:

  XMLHttpRequest cannot load http://t00-holcim:8888/deliveries?fields=liefer_nr,dispo_nr,lieferscheinsta…r,empfaenger_nr,bestellinfo1,bemerkung&limit=3&deliveryNoteDate=2017-04-27. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

Here's the program code:

....... 
const headers = new Headers(); 
headers.append('Content-Type', 'application/json; charset=utf-8'); headers.append('Access-Control-Allow-Origin', '*'); 
const options = new RequestOptions({ method: RequestMethod.Post, headers: headers });

this.http.get(this.buildURLString(), options).map(this.extractData)
              .subscribe((data) => {........}

I searched the net and I found that the error is related to CORS. Therefore I append to the header headers.append('Access-Control-Allow-Origin', '*'); but this does not help.

I got extension CORS for Chrome and enable "Enable cross origin resource sharing" but it didn't help.

Is this a configuration change on the server side or client side.

2条回答
SAY GOODBYE
2楼-- · 2019-05-23 11:33

It is a server side issue. Which language are you using for your server? If you are using JS the below block takes care of CORS issue.

var app = express()    
var cors = require('cors');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, 
Content-Type, Accept");
next();
});
查看更多
Deceive 欺骗
3楼-- · 2019-05-23 11:43

We found the solution. As we are using the RESTFul-Server of SpringBoot, to this server we added the "'Access-Control-Allow-Origin', '*'" and it worked.. I was always thinking because it says "preflight" that this need to be solved on the client side and not on the server side.
Hope this helps anybody.

查看更多
登录 后发表回答