Angular HttpClient 不会向控制器发送数据。当我尝试执行 fun() 时,我收到错误 500(因为控制器中的用户名为空)。
测试服务.ts
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class RestService {
private EndPointUrl = 'http://127.0.0.1:8080/api/test';
constructor(public http: HttpClient){}
fun(){
this.test().subscribe((data)=>console.log(data));
}
test(): Observable<string>{
let params = new URLSearchParams();
params.append("grant_type",'password');
params.append('username', 'Name');
let body = params.toString();
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<string>(this.EndPointUrl, body);
}
}
包.json
...
"dependencies": {
"@angular/common": "4.3.4",
"@angular/compiler": "4.3.4",
"@angular/compiler-cli": "4.3.4",
"@angular/core": "4.3.4",
"@angular/forms": "4.3.4",
"@angular/http": "4.3.4",
"@angular/common/http": "4.3.4",
"@angular/platform-browser": "4.3.4",
"@angular/platform-browser-dynamic": "4.3.4",
...},
Spring MVC 控制器:
@RequestMapping(value="/test",
method = RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE)
public String[] test(HttpServletRequest request){
Map<String, String[]> parameters = request.getParameterMap();
return parameters.get("username");
}
来自 postMan 的请求有效,并返回一些用户名。
有谁知道我做错了什么?