简体   繁体   中英

POST request from angular to spring rest api

I have created a REST API in Spring Bboot and a client application in Angular 4. I am running both the applications locally. When I test the POST method from postman it works well, however when I make a POST request from the Angular 4 app it results in 400 Bad request . The REST API displays the following error at the console as

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

The REST API has a POST method as below:

@CrossOrigin(origins = "*")
    @RequestMapping(value="/api/newcustomer", method=RequestMethod.POST, consumes= "application/json")
    public Customer addCustomer(@RequestBody Customer customer){
        System.out.println("***********"+customer.getFirstName());
        return customer;
    }

The Angular service

@Injectable()
export class PostdataService {

  constructor(private _http : Http) {}

  postContactFormData(firstName, lastName, accounts, phoneNumber){
    var body : {firstName , lastName, accounts, phoneNumber};
    var headers = new Headers({ 'Content-Type': 'application/json' });
    return this._http.post('http://localhost:8080/api/newcustomer/', JSON.stringify(body),{
        headers : headers
    }).subscribe(
        () =>{},
        err => console.error(err)
    );
  }

}

The Customer class

public class Customer {

     private String firstName;
     private String lastName;
     private String phoneNumber;
     private List<Account> accounts;

     public Customer(){

     }

Run your request body through a linter such as jsonlint.com.

The request you are attempting to stringify is not valid json {firstName , lastName, accounts, phoneNumber} should be something like this:

{"firstName": "firstName", "lastName": "lastName", "accounts": [1, 2, 3], "phoneNumber": 1.800.123.4567}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM