【发布时间】:2018-03-11 05:26:06
【问题描述】:
我正在尝试使用 angularjs4 发送发布请求。代码在到达login() 函数时运行良好。注意this.http.post 函数,如果我删除最后一个参数,即使请求看起来像return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }),那么 web api 上的请求标头变为:
POST /auth HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 39
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */\*
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
content-type: text/plain
Referer: http://localhost:4200/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
注意 content-type:text/plain 默认由 angularjs 设置。所以我尝试添加{ headers: head} 以将content-type 更改为application/json,这反过来将Invalid CORS request 显示为响应并将Request Header 更改为:
Accept:*/\*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
.
.
注意Access-Control-Request-Headers:content-type 行,这当然是错误的。
下面是发起请求的授权文件:
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, RequestMethod } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthenticationService {
public token: string;
constructor(private http: Http) {
}
login(username: string, password: string): Observable<boolean> {
let head = new Headers({ 'Content-Type': 'application/json' });
return this.http.post('http://localhost:8080/auth', JSON.stringify({ username: username, password: password }),{ headers: head})
.map((response: Response) => {
// login successful if there's a jwt token in the response
let token = response.json() && response.json().token;
console.log(response);
});
}
}
请在通过 AngularJS 4 发布请求的请求标头中建议将内容类型更改为 application/json 的正确方法
【问题讨论】:
标签: angular post http-headers content-type