0

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 的请求有效,并返回一些用户名。

有谁知道我做错了什么?

4

2 回答 2

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);
    }); }
于 2017-08-18T08:46:14.253 回答
0

使用Http而不是HttpClient

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

constructor(private http: Http) { }

...
于 2017-08-18T10:06:52.653 回答