I have a problem to read the data I sent via curl request in nodejs. With Postman everything is working properly, but when I try to send request via curl, the api return 500 internal server error and I don’t know where is the mistake.
so here is my php code
private function curl($url, $post = false, $header = false) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); if ($post) { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post)); } curl_setopt($ch, CURLOPT_HEADER, [ 'Content-Type: application/json', 'Accept: application/json', 'Content-Length: ' . mb_strlen(json_encode($post)) ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec ($ch); curl_close($ch); return $response; }
so now I will share with you the part of nodejs
console.log(req.body) let content = req.body.content if (!content.length) { return res.status(401).send({message: 'content is required'}) }
and here is the log info
{ '{"content":"content information"}': '' }
2020-08-18T07:27:38.191100+00:00 app[web.1]: TypeError: Cannot read property ‘length’ of undefined. I don’t know where is my mistake, and why I can not read json data on node js, any help will be appriciate.
Advertisement
Answer
It would appear that you are not properly adding the body to your request in php/curl. As a result, req.body.content
is undefined
. Accessing a property on undefined
throws your error, so you need to check for that possibility in your JS code, but the real issue in your system is that you aren’t sending a body in php. Hopefully that helps you get to the root of the problem and you can figure out how to attach the body data to your request from there.