且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 2令牌:飞行前响应具有无效的HTTP状态代码400

更新时间:2021-10-20 05:24:07

我找到了解决方案.感谢API网站上的评论: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

I found the solution. Thanks to the comments on the API site: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api

我必须为 application/x-www-form-urlencoded设置正确的标头; charset = UTF-8 并序列化我发布的对象.我找不到Angular序列化器方法,所以我用JavaScript制作了自己的副本(从另一个***网站复制).

I had to set the correct header for application/x-www-form-urlencoded; charset=UTF-8 and serialize the object i posted. I can´t find an Angular serializer method, so I made my own(copy from another *** site) in JavaScript.

当用户使用Angular2& 2登陆API并请求令牌时,这是最后的调用.打字稿:

Here is the final call when the user login on the API and request a token, when using Angular2 & TypeScript:

 loginAccount(account: Account): Observable<string> {        
    var obj = { UserName: account.Email, Password: account.Password, grant_type: 'password' };

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
        let options = new RequestOptions( {method: RequestMethod.Post, headers: headers });

        let body = this.serializeObj(obj);

         return this._http.post('https://localhost:44305/Token',  body, options)
                             .map(this.extractData)
                             .catch(this.handleError);
}

private serializeObj(obj) {
    var result = [];
    for (var property in obj)
        result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));

    return result.join("&");
}