我有一个运行Visual Studio Code的Angular2 / TypeScript应用程序。
在VS 2015中运行的API。这是API项目:http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
我可以使用API并创建新用户,但是当我尝试登录(使用令牌功能)时,我收到以下错误:XMLHttpRequest无法加载https://localhost:44305/Token。预检的响应具有无效的HTTP状态代码400
标题看起来像这样:
Request URL:https://localhost:44305/Token
Request Method:OPTIONS
Status Code:400
Remote Address:[::1]:44305
Response Headers
cache-control:no-cache
content-length:34
content-type:application/json;charset=UTF-8
date:Wed, 10 Aug 2016 19:12:57 GMT
expires:-1
pragma:no-cache
server:Microsoft-IIS/10.0
status:400
x-powered-by:ASP.NET
x-sourcefiles:=?UTF-8?B?QzpcQ2hlY2tvdXRcQVBJXzJ2czJcQVBJXEFQSVxUb2tlbg==?=
Request Headers
:authority:localhost:44305
:method:OPTIONS
:path:/Token
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, sdch, br
accept-language:en-US,en;q=0.8,da;q=0.6,nb;q=0.4
access-control-request-headers:authorization
access-control-request-method:POST
cache-control:no-cache
origin:http://evil.com/
pragma:no-cache
referer:http://localhost:3000/signin
user-agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
我的角度服务看起来像这样:
loginAccount(account: Account): Observable<string> {
var obj = { Email: account.Email, Password: account.Password, grant_type: 'password' };
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions( {method: RequestMethod.Post, headers: headers });
let body = JSON.stringify(obj);
console.log('loginAccount with:' + body);
return this._http.post('https://localhost:44305/Token', body, options)
.map(this.extractData)
.catch(this.handleError);
}
当我在API项目中使用AJAX函数时:qazxsw poi然后它工作得很好??我在Angular POST请求中做错了什么?
我找到了解决方案。感谢API网站上的评论:http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
我必须为application / x-www-form-urlencoded设置正确的标题; charset = UTF-8并序列化我发布的对象。我找不到Angular序列化器方法,所以我在JavaScript中创建了自己的(从另一个stackoverflow站点复制)。
以下是用户登录API并在使用Angular2和TypeScript时请求令牌的最终调用:
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
我上周也遇到了同样的问题,搜索谷歌和堆栈溢出但所有解决方案都是静脉。但经过大量的阅读和调查我们发现下面的解决方案,我们只在POST方法面临问题,GET调用成功。
而不是直接传递选项,我们需要首先字符串化选项对象,如JSON.stringify(选项)
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("&");
}
它对我有用,希望它也能帮助别人。
我发现在角度4中你必须这样做。
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);
}
另一种原生解决方案是使用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);
}
类和它的HttpParams方法:
toString()
toString() - 将主体序列化为编码字符串,其中键值对(由=分隔)由&s分隔。
注意。它也可以不设置标题