Web API 2上的Angular 2 HTTP Post - 错误请求

时间:2016-09-27 14:56:24

标签: angular typescript asp.net-web-api2 angular2-services

我正在尝试使用角度2调用web api身份验证,如下所示。但是我收到了错误

“无法加载资源:服务器响应状态为400(错误请求)”

身份验证服务正在本地IIS服务器上运行。

这里有什么遗漏?

import { Injectable } from '@angular/core';
import {Http, Response, RequestOptions, Request, RequestMethod, Headers, HttpModule} from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';



@Injectable()
export class AuthService {
    public token: string;

    constructor(private http: Http) {
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
    }

    login(username, password): Observable<boolean> {
        var authObj = {
            username: username, Password: password, grant_type : 'password'
        }

        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post('http://localhost/Authentication/oauth/Token', JSON.stringify({ username: username, Password: password, grant_type: 'password' }), options)
            .map((response: Response) => {

                let token = response.json() && response.json().token;

                if (token) {
                    //set the token property 
                    this.token = token;
                    //user username and jwt token in local storage to keep user loggen in between page refreshes
                    localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token }));
                    //return true to indicate the successful login
                    return true;
                } else {
                    //return false to indicate failed login
                    return false;
                }
            });
        }

    logout(): void {
        this.token = null;
        localStorage.removeItem('currentUser');
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个 -

let headers = new Headers({'Content-Type':'application / x-www-form-urlencoded'});