Angular4不发送帖子数据

时间:2017-08-18 08:07:40

标签: spring angular spring-mvc angular-httpclient

Angular HttpClient不会将数据发送到控制器。 当我尝试执行fun()时,我收到错误500(因为控制器中的用户名为空)。

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");
}

来自postMan的请求工作,并返回一些用户名。

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:1)

我能看到的是你没有正确使用HttpClient ...因为它有角度4.3。*并且与旧版Http略有不同..

你不必再做.json() ..例如:

    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);
}); }

然后你的帖子:

                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);
    }); }

答案 1 :(得分:0)

使用Http代替HttpClient

import {Http} from '@angular/http';
...

constructor(private http: Http) { }

...