没有Access-Control-Allow-Origin for angular-cli“localhost:4200”

问题描述 投票:2回答:2

我有一个与CORS和所需标题有关的问题。

设置我运行一个角度项目和angular-cli(localhost:4200)我想通过HTTP服务从WebService访问一个JSON。当我在浏览器中直接使用URL时,一切都很好,并显示JSON。一旦我从angular-app发送请求,我就会收到以下错误:

  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.

这是程序代码:

....... 
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) => {........}

我在网上搜索,发现错误与CORS有关。因此我附加到头文件header.append('Access-Control-Allow-Origin','*');但这没有用。

我获得了Chrome的扩展CORS并启用了“启用跨源资源共享”,但它没有帮助。

这是服务器端还是客户端的配置更改。

angular http angular-cli
2个回答
1
投票

我们找到了解决方案。当我们使用SpringBoot的RESTFul-Server时,我们在这个服务器上添加了“'Access-Control-Allow-Origin', '*'”并且它有效。我一直在想,因为它说“预检”这需要在客户端解决,而不是在服务器端。 希望这可以帮助任何人。


0
投票

这是服务器端问题。您使用哪种语言服务器?如果您使用JS,则以下块将处理CORS问题。

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();
});
© www.soinside.com 2019 - 2024. All rights reserved.