spring - Angular4 doesn't send post data -


angular httpclient doesnt send data controller. error 500 (because username in controller null) when try execute fun().

test.sevice.ts

import { injectable } '@angular/core'; import {httpclient} "@angular/common/http";  import 'rxjs/rx'; import { observable } '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 postman works, , returns username.

does know i'm doing wrong?

what can see you're using httpclient not correctly ... cause came in angular 4.3.* , little bit different old http ..

you don't have anymore .json() ..so example:

    return this.http.post<string>(this.endpointurl,  body) //<-- don't need headers f.. itknows it's application/x-www-form-urlencoded        .map((resp) => {     return resp;  //<-- here resp resp.json()     })        .catch((err)=>{ console.log(err); }); } 

and post:

                let dataform = new urlsearchparams();                   dataform.append('username', "myusername");                  let body = dataform.tostring();     return this.http.post<string>(this.endpointurl,  body) //<-- don't need headers f.. itknows it's application/x-www-form-urlencoded            .map((resp) => {         return resp;  //<-- here resp resp.json()         })            .catch((err)=>{     console.log(err);     }); } 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -