Angular2 Http设置头部Access-Control-Allow-Origin和http CORS

时间:2016-08-14 06:44:05

标签: angularjs angular http-headers

我正在使用Angular2 RC5(核心,http等)并尝试连接到启用CORS的Node.js服务器。我的应用程序是从Angular-CLI生成的新版本(版本:“1.0.0-beta.11-webpack.2”)。

// src/app/app.component.ts
...
ngOnInit () {
   const headers: Headers = new Headers();
   headers.append('Accept', 'application/json');
   headers.append('Content-Type', 'application/json');
   headers.append('Access-Control-Allow-Origin', '*');

   const options = new RequestOptions({
     headers: headers
   });

   this.http.get('http://localhost:9000/api/v1/users', options)
    .map((res: Response) => res.json())
    .subscribe(users => console.log(users));
}

...

当应用程序启动时,OnInit挂钩被调用,我在控制台中出错。这是我收到的错误消息。

EXCEPTION: TypeError: Cannot read property 'toString' of null
browser_adapter.js:84EXCEPTION: TypeError: Cannot read property 'toString' of nullBrowserDomAdapter.logError @ browser_adapter.js:84BrowserDomAdapter.logGroup @ browser_adapter.js:94ExceptionHandler.call @ exception_handler.js:65(anonymous function) @ application_ref.js:267ZoneDelegate.invoke @ zone.js:323onInvoke @ ng_zone_impl.js:53ZoneDelegate.invoke @ zone.js:322Zone.run @      zone.js:216(anonymous function) @ zone.js:571ZoneDelegate.invokeTask @ zone.js:356onInvokeTask @ ng_zone_impl.js:44ZoneDelegate.invokeTask @ zone.js:355Zone.runTask @ zone.js:256drainMicroTaskQueue @ zone.js:474
zone.js:461 Unhandled Promise rejection: Cannot read property 'toString' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'toString' of null(…)consoleError @ zone.js:461_loop_1 @ zone.js:490drainMicroTaskQueue @ zone.js:494
zone.js:463 Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null(…)

如果我完全退出optionsheader,我收到了CORS错误,但服务器的响应状态为200。 (我想如果我可以传递正确的标题,它应该可以工作。)

 this.http.get('http://localhost:9000/api/v1/users')
  .map((res: Response) => res.json())
  .subscribe(users => console.log(users)); 

以下是控制台的错误

XMLHttpRequest cannot load http://localhost:4000/api/v1/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
browser_adapter.js:93EXCEPTION: Response with status: 0  for URL: null
browser_adapter.js:84EXCEPTION: Response with status: 0  for URL: nullBrowserDomAdapter.logError @         browser_adapter.js:84BrowserDomAdapter.logGroup @    browser_adapter.js:94ExceptionHandler.call @ exception_handler.js:65next @ application_ref.js:348schedulerFn @ async.js:89SafeSubscriber.__tryOrUnsub @ Subscriber.js:225SafeSubscriber.next @ Subscriber.js:174Subscriber._next @ Subscriber.js:124Subscriber.next @ Subscriber.js:88Subject._finalNext @     Subject.js:128Subject._next @ Subject.js:120Subject.next @ Subject.js:77EventEmitter.emit @ async.js:77onHandleError @ ng_zone_impl.js:74ZoneDelegate.handleError @ zone.js:327Zone.runTask @ zone.js:259ZoneTask.invoke @ zone.js:423
Subscriber.js:229Uncaught Response with status: 0  for URL: null

有人可以帮忙吗?感谢。

3 个答案:

答案 0 :(得分:4)

我是新手,请耐心等待,但就我而言,后端Node.js服务器应返回Access-Control-Allow-Origin标头。由于安全性,默认情况下禁用服务器端的CORS。 使用以下问题来帮助您实施:How to allow CORS?

答案 1 :(得分:1)

您的问题是由rc5中引入的错误引起的。修改了XHRBackend Http以将任何请求的正文转换为字符串。它会查看Content-Type标头并尝试调用相应的转换方法。

在上面的代码中,您将Content-Type标头设置为application/json,这会导致XHRBackend尝试将其转换为字符串。但是,由于您正在发出GET请求,body为空,因此会抛出此异常。

在您的情况下,只需删除Content-Type标题,一切都应该正常。

答案 2 :(得分:1)

这里写的是:

https://github.com/angular/angular/issues/10612

解决问题

EXCEPTION: TypeError: Cannot read property 'toString' of null

您需要将正文设置为&#39;&#39;

headers.append('body', '');