我在Spring Bboot中创建了一个REST API,在Angular 4中创建了一个客户端应用程序。我在本地运行这两个应用程序。当我从POST
测试postman
方法时效果很好,但是当我从Angular 4应用程序发出POST
请求时,会产生400 Bad request
。 REST API在控制台上显示以下错误
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing
REST API有一个POST方法,如下所示:
@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;
}
Angular服务
@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)
);
}
}
Customer
班
public class Customer {
private String firstName;
private String lastName;
private String phoneNumber;
private List<Account> accounts;
public Customer(){
}
答案 0 :(得分:0)
通过诸如jsonlint.com之类的linter运行您的请求正文。
您尝试stringify的请求无效json
{"firstName": "firstName", "lastName": "lastName", "accounts": [1, 2, 3], "phoneNumber": 1.800.123.4567}
应该是这样的:
props