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

后端 未结 4 2047
予麋鹿
予麋鹿 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:26

    I was also facing same issue from last week and searched on google and stack overflow but all solutions in vein. but after lot of reading and investigation we have found below solution, we were facing issue in only POST method,GET called successfully.

    Instead of directly passing Options we need to first stringify option object like JSON.stringify(options)

    CreateUser(user:IUser): Observable<void> {
            let headers = new Headers();
            headers.append('Content-Type', 'application/json');
            headers.append('Accept', 'application/json');
            let options = new RequestOptions({ headers: headers });
            return this._http.post('http://localhost:22736/api/Employee/Create', **JSON.stringify(options)**)
                .map((res: Response) => {
                    return res.json();
                })
                .catch(this.handleError);
        }
    

    It worked for me, Hope it will help others too.

    0 讨论(0)
  • 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<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("&");
    }
    
    0 讨论(0)
  • 2021-02-09 11:34

    I found that in angular 4 you have to make it like this.

    public addQuestion(data: any): Observable<Response>  {
    
        let headersObj = new Headers();
        headersObj.set('Content-Type', 'application/x-www-form-urlencoded');
    
        let requestArg: RequestOptionsArgs = { headers: headersObj, method: "POST" };
    
        var params = new URLSearchParams();
        for(let key of Object.keys(data)){ 
          params.set(key,data[key]);
        };
    
        return this.http.post(BaseApi.endpoint + 'Question', params.toString(), requestArg)
        .map((res: Response) => res.json().data);
    
      }
    
    0 讨论(0)
  • 2021-02-09 11:38

    Another native solution is by using HttpParams class and it's toString() method:

     let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
        let options = { headers, observe: 'response' };
    
       const body = new HttpParams()
          .set('grant_type', 'password')
          .set('username', accountInfo.username)
          .set('password', accountInfo.password);
    
        return this._http.post('https://localhost:44305/Token',  body.toString(), options)
    

    toString() - Serialize the body to an encoded string, where key-value pairs (separated by =) are separated by &s.

    Note. Also it works without setting the headers

    0 讨论(0)
提交回复
热议问题