Angular2发送帖子请求时遇到的问题

时间:2016-08-04 11:44:59

标签: typescript angular

我有一个简单的代码,用于向本地服务器发送邮件请求。 像这样:

  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());
        }
      );
  }

但我在google chrome dev控制台中捕获了下一个异常。

  

XMLHttpRequest无法加载http://localhost:1216/api/Login。响应   for preflight具有无效的HTTP状态代码400

请帮我解决这个问题,因为Angular 1.x一切正常。 从谷歌Chrome控制台登录:

   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:

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 从高级REST客户端登录

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

2 个答案:

答案 0 :(得分:1)

你可能错过了另一个标题:

"Access-Control-Allow-Methods", "POST"

查看CORS enabled but response for preflight has invalid HTTP status code 404 when POSTing JSON了解详情

更新:也许只是这个。请检查此回答https://stackoverflow.com/a/37654548/1267942

答案 1 :(得分: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>

从startup.cs类中删除 app.UseCors(CorsOptions.AllowAll); 。 非常感谢,所有人都花时间解决我的问题;)