问题
Angular HttpClient doesnt send data to controller. I get a error 500 (because username in controller is null) when i try to execute fun().
test.sevice.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);
}
}
package.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 Controller:
@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");
}
Request from postMan works, and returns some username.
Does anyone know what I'm doing wrong?
回答1:
What i can see is you're using HttpClient not correctly ... cause it came in angular 4.3.* and is little bit different from the old Http
..
you don't have to do anymore .json()
..so for example:
return this.http.post<string>(this.EndPointUrl, body) //<-- IT DON'T NEED HEADERS F.. ITKNOWS IT'S A application/x-www-form-urlencoded
.map((resp) => {
return resp; //<-- HERE resp is your resp.json()
})
.catch((err)=>{
console.log(err);
}); }
and then your post:
let dataForm = new URLSearchParams();
dataForm.append('userName', "MyUserName");
let body = dataForm.toString();
return this.http.post<string>(this.EndPointUrl, body) //<-- IT DON'T NEED HEADERS F.. ITKNOWS IT'S A application/x-www-form-urlencoded
.map((resp) => {
return resp; //<-- HERE resp is your resp.json()
})
.catch((err)=>{
console.log(err);
}); }
回答2:
use Http
instead of HttpClient
:
import {Http} from '@angular/http';
...
constructor(private http: Http) { }
...
来源:https://stackoverflow.com/questions/45751648/angular4-doesnt-send-post-data