在angular2上设置http标头

时间:2017-02-02 08:52:08

标签: angular angular2-services

在我的应用程序中,我有一个在webService上构建的列表,并希望使用Angular2获取http。 我为此创建了一个服务,这是我为它编写的代码:

我的http服务:

import { Injectable, Inject } from '@angular/core';
import { RequestOptionsArgs, Http, Response, RequestOptions, Request, RequestMethod, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { StaticValuesService } from './static-values.service';
import { Building } from '../model/building';

@Injectable()
export class BuildingService {

  constructor(private _http: Http, private _values: StaticValuesService) {}

  getAllBuildings() {

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this._http.get(this._values.MainApi + 'api/getbuildings/', options)
      .map((response: Response) => response.json());

  }

}

我使用此代码订阅了一个组件:

constructor(private _buildingServices: BuildingService) { }

  ngOnInit() {
    this._buildingServices.getAllBuildings().subscribe(res => {
      console.log(res);
    }, error => {
        console.log(error);
    });
  }

运行角度服务器之后看起来contnet-type未在请求的标头中设置!并且结果是控制台上出现404错误!

enter image description here

在网络Chrome中请求内容

OPTIONS /api/getbuildings/ HTTP/1.1
Host: nommix-api.azurewebsites.net
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
Access-Control-Request-Headers: authorization, content-type
Accept: */*
Referer: http://localhost:4200/dashboard/master
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en,en-US;q=0.8,fa;q=0.6
AlexaToolbar-ALX_NS_PH: AlexaToolbar/alx-4.0

回复标题:

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 134
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Set-Cookie: ARRAffinity=12a1bb0d03776b567fa3d04e126a9fa5ad153cba2c87fbc48fc25d775bebd44a;Path=/;Domain=nommix-api.azurewebsites.net
Date: Thu, 02 Feb 2017 11:51:25 GMT

当我使用Postman测试API时,它正常工作。

为什么它不起作用?我该如何修复?

谢谢。

1 个答案:

答案 0 :(得分:1)

假设您通过本教程https://github.com/angular/angular-cli#proxy-to-backend

配置代理

尝试在后端webservice中启用CORS

Access-Control-Allow-Methods: GET, POST, OPTIONS

在ASP.net应用中启用OPTIONS方法 https://stackoverflow.com/a/21458845/3676586

相关问题