Angular 2 Token: Response for preflight has invalid HTTP status code 400

后端 未结 4 2048
予麋鹿
予麋鹿 2021-02-09 10:45

I have an Angular2/TypeScript application running i Visual Studio Code.

An API running in VS 2015. This is the API project: http://www.asp.net/web-api/overview/security/

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-09 11:34

    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

    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 stackoverflow site) in JavaScript.

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

     loginAccount(account: Account): Observable {        
        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("&");
    }
    

提交回复
热议问题