user1609085 user1609085 - 8 months ago 151
Node.js Question

Sending @RequestBody from node js to Spring Boot Rest API

After spending more than half a day still not able to get down to whats wrong with the following:

Trying to send form data from NodeJSto Spring Rest API.

Node JS:

var inputData = { base : req.body.base, test : req.body.test }

var queryParams = {
host: '127.0.0.1',
port: 8080,
path: '/start',
method: 'POST',
headers: {'Content-type': 'application/json'},
body: inputData //Used JSON.stringify(inputData) - didn't work
};


Using http module to send request:

var req = http.request(queryParams, function(res) {
//do something with response
});
req.end();


Spring Rest:

@RequestMapping(value = "/start", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String startApp(@RequestBody String body) {
System.out.println(body);

return "{\"msg\":\"Success\"}";
}


Using postman I am able to see the same inputData going through the Rest. But when sent from NodeJS, all I see is

{
timestamp: 1506987022646,
status: 400,
error: 'Bad Request',
exception: 'org.springframework.http.converter.HttpMessageNotReadableException',
message: 'Required request body is missing: public java.lang.String ApplicationController.startApp(java.lang.String)',
path: '/start'
}


Using spring-boot-starter parent in the maven.

Am I missing anything here? Any suggestions would be greatly appreciated!

Answer Source

I don't think that you put request body in queryParams will work.
You can try using req.write() to write data to request body as follows:

...  
req.write(inputData);  
req.end();
... 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download