2016-08-04 100 views
0

我有一个简单的代码发送post请求到我的本地服务器。 像这样:Angular2发送post请求的问题

login(event, username, password) { 
    event.preventDefault(); 
    let body = "grant_type=password&username=" + username + "&password=" + password; 
    this.http 
     .post(`${appSettings.API_ENDPOINT_DEV}Login`, body, {headers: contentHeaders}) 
     .subscribe(
     response => { 
      this.accessToken = response.json().access_token; 
      console.log(this.accessToken); 
      localStorage.setItem('access_token', this.accessToken); 
     }, 
     error => { 
      alert(error.text()); 
      console.log(error.text()); 
     } 
    ); 
    } 

但是我赶上谷歌浏览器开发者控制台中的下一个异常。

XMLHttpRequest无法加载http://localhost:1216/api/Login。预检响应 无效HTTP状态码400

帮助,因为有角1.x的所有工作以及我请解决这个问题。从谷歌浏览器的控制台 登录:

Request URL:http://localhost:1216/api/Login 
    Request Method:OPTIONS 
    Status Code:400 Bad Request 
    Remote Address:[::1]:1216 
    Access-Control-Allow-Origin:* 
    Cache-Control:no-cache 
    Content-Length:34 
    Content-Type:application/json;charset=UTF-8 
    Date:Thu, 04 Aug 2016 11:43:21 GMT 
    Expires:-1 
    Pragma:no-cache 
    Server:Microsoft-IIS/10.0 
    X-Powered-By:ASP.NET 
    X-SourceFiles:=?UTF-8?B?RDpcU291cmNlc1xHcmFwcHNcVUtfQnJhbmRQcm90ZWN0aW9uXFdlYkFQSVxhcGlcTG9naW4=?= 

UPD:从先进的REST客户

export const contentHeaders = new Headers(); 
contentHeaders.append('Content-Type', 'application/x-www-form-urlencoded'); 
contentHeaders.append('Access-Control-Allow-Origin', '*; *'); 
contentHeaders.append('Access-Control-Allow-Methods', 'POST'); 

UPD2 登录

Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json;charset=UTF-8 
Expires: -1 
Server: Microsoft-IIS/10.0 
Access-Control-Allow-Origin: *; * 
X-Sourcefiles: =?UTF-8?B?RDpcU291cmNlc1xHcmFwcHNcVUtfQnJhbmRQcm90ZWN0aW9uXFdlYkFQSVxhcGlcTG9naW4=?= 
X-Powered-By: ASP.NET 
Access-Control-Allow-Headers: Content-Type 
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS 
Date: Thu, 04 Aug 2016 11:59:19 GMT 
Content-Length: 316 
+0

您需要正确配置您的服务器http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control -allow-origin –

+0

与Angular 1.x一切正常。请再读一遍我的问题。 –

+0

如何定义'contentHeaders'? – kiswa

回答

0

我发现的问题我已经增加了一些配置到Web.config:

<httpProtocol> 
      <customHeaders> 
       <add name="Access-Control-Allow-Origin" value="*" /> 
       <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
       <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> 
      </customHeaders> 
     </httpProtocol> 

,并删除app.UseCors(CorsOptions.AllowAll);来自startup.cs类的。 非常感谢,各国人民花时间为我的问题;)