我正在尝试使用Angular8前端对Java后端进行登录调用。 该功能在Postman中可以正常工作,但在Angular中可以抛出400。 呼叫看起来像这样:
login(username: string, password: string) {
let headers = new HttpHeaders();
headers.set("Content-Type", "application/x-www-form-urlencoded");
headers.set("Accept", "application/json");
let options = {
headers: headers,
params: new HttpParams()
}
let payload = {"username": username, "password": password};
let response = this.http.post<any>(environment.BASE_URL+'/api/auth/login', payload, options);
console.log(response);
return response;
}
当我查看浏览器控制台时,我的请求如下:
POST /api/auth/login HTTP/1.1 Host: localhost:8080 Connection:
keep-alive Content-Length: 37 Accept: application/json, text/plain,
*/* Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36
Content-Type: application/json
Referer: http://localhost:4200/login Accept-Encoding: gzip, deflate,
Accept-Language: en-US,en;q=0.9,pl;q=0.8
由于某些原因,我定义的标头不包括在内,内容类型为默认的“ application / json”,而不是我想要的x-form。有效负载存在,但选项不存在。那可能是错误的原因,所以为什么我的标头不被接受,这是怎么回事?
答案 0 :(得分:4)
假设您的后端看起来像这样:
@RequestMapping(path = "/api/auth/login", method = RequestMethod.POST)
public Collection getLoginData(@RequestParam("username") String username,
@RequestParam("password") String password) {
return this.service.getLoginData(username, password);
}
尝试使用FormData
public getLoginData(username: string, password: string): any {
const data = new FormData();
data.append('username', username);
data.append('password', password);
return this.http.post<any>(environment.BASE_URL + '/api/auth/login', data);
}
答案 1 :(得分:1)
尝试此代码。您必须设置对原始对象的引用。
login(username: string, password: string) {
let headers = new HttpHeaders();
headers = headers.append("Content-Type", "application/x-www-form-urlencoded");
headers = headers.append("Accept", "application/json");
let options = {
headers: headers,
params: new HttpParams()
}
let payload = {"username": username, "password": password};
let response = this.http.post<any>(environment.BASE_URL+'/api/auth/login', payload, options);
console.log(response);
return response;
}
答案 2 :(得分:0)
因此,一个真正有效的示例如下:
login(username: string, password: string): Observable<LoggedUser> {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers = headers.append('Accept', 'application/json');
let params = new HttpParams();
params = params.set('username', username);
params = params.set('password', password);
const options = {
headers,
params
};
return this.http.post<LoggedUser>(environment.BASE_URL + '/api/auth/login', {}, options);
}