0

i wanna post a simple http request , but the backend can not receive the paramter

export class AppComponent {
  isMenuCollapsed$:Observable<boolean>;

  constructor(private store:Store<reducers.State>,private http:Http) {

    this.isMenuCollapsed$ = this.store.select(reducers.getIsCollapsed);
    let body: URLSearchParams = new URLSearchParams();

    body.set('username', 'admin');
    body.set('password', 'admin');
    let head = new Headers({
      'Content-Type': 'application/json'
    });
    http.post('api/user/auth',body).subscribe(v => console.log(v));
  }
}

this is my backend code:

@RestController
@RequestMapping("/user")
public class TestController {

    @GetMapping("/get")
    public String  test(){
        return "hello";
    }

    @PostMapping("/auth")
    public String  auth(HttpServletRequest request){
        return "username:" + request.getParameter("username") + 
                "|password:" + request.getParameter("password");
    }
}

when i use regular method it worked:

enter image description here

but when i use angular http , return null enter image description here

so i hope someone can help me , thanks!!!

3
  • I don't think your code is right, because in POST methods you are supposed to be saving a response body that is wrapped in your data model for persistence. That also means that in your post you ought to be creating an object for persistence. Commented Jul 19, 2017 at 3:40
  • thanks very much , i just post an object and add @RequestBody annotation in the backend code . . and it working ! ^_^ Commented Jul 19, 2017 at 5:24
  • can you pick my answer and have ourselves a nice day? :) Commented Jul 19, 2017 at 12:24

2 Answers 2

0

I think instead og getParameters you should use something to get body of request. create simple object of username and password like

let body={username:"admin", password:"admin"}

Stringify body before passing to request.

this.http.post(...., Json.stringify(body))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks very much , i just post an object and add @RequestBody annotation in the backend code . . and it working ! ^_^
0

You need to make the backend and front end post the object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.