1

I'm want to make a POST request to my REST API but I'm getting the error that The REST API is made in Spring I have an unexpected token :

POST Request Call :

http://localhost/users/load

Java Code:

@PostMapping(value = "/load")
public User load(@RequestBody final User user){
    userRepository.save(user);
    return userRepository.findByName(user.getName());
}

User Class:

@Entity
public class User {
private Long id;
private String name;
private String username;
private String password;

@Id
@GeneratedValue
public Long getId(){
    return id;
}

public void setId(Long id){
    this.id = id;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name = name;
}

public String getUsername(){
    return username;
}

public void setUsername(String username){
    this.username = username;
}

public String setPassword(){
    return password;
}

public void getPassword(){
    this.password = password;
}
}

JSON data:

{
    "name": "John", 
    "username": "randomUsername", 
    "password": "Password123!"
}

Postman: enter image description here

Error:

There was an error in evaluating the test script:  SyntaxError: Unexpected token :

I expected that the request should pass but it didn't

Tom van den Bogaart
  • 143
  • 1
  • 4
  • 15
  • check you test block in postman looks like a test is failing. This error has nothing to do with spring. – Grinish Nepal Sep 04 '19 at 19:35
  • @GrinishNepal the error I'm getting { "timestamp": "2019-09-04T19:51:51.787+0000", "status": 400, "error": "Bad Request", "message": "Required request body is missing: public com.spring.timelybackend.models.User com.spring.timelybackend.controllers.UserController.load(com.spring.timelybackend.models.User)", "path": "/users/load" } – Tom van den Bogaart Sep 04 '19 at 19:52
  • 1
    You might need to ignore the id from the entity so maybe `@JsonIgnore` from jackson might help you. The error is straight forwd wrong request model which is user. – Grinish Nepal Sep 04 '19 at 20:12
  • Please also post the screenshot of how you sent the POST request in Postman. – LHCHIN Sep 05 '19 at 01:00
  • @LHCHIN check updated version – Tom van den Bogaart Sep 05 '19 at 06:46
  • The answer was found [in another question](https://stackoverflow.com/questions/52974330/spring-post-method-required-request-body-is-missing/52974492) – Tom van den Bogaart Sep 05 '19 at 07:08
  • @Tom van den Bogaart That's why I requested you to provide the screenshot of Postman. :) – LHCHIN Sep 05 '19 at 09:08

1 Answers1

3

Because you are adding request body in tests tab,

Request body must be in body tab then select raw, and paste you json also add header in headers tab content-type : application/json

Please check this sample

Postman ref

Tests tab is for writing JavaScript code to assert if body is what i expected in order to test my app.

Yasser Mas
  • 1,652
  • 1
  • 10
  • 14