The question is answered. But since it is quite generic and req.body
undefined is a frequent error, especially for beginners, I find this is the best place to resume all that I know about the problem.
This error can be caused by the following reasons:
1. [SERVER side] [Quite often] Forget or misused parser middleware
- You need to use appropriate middleware to parse the incoming requests. For example,
express.json()
parses request in JSON format, andexpress.urlencoded()
parses request in urlencoded format.
const app = express();app.use(express.urlencoded())app.use(express.json())
You can see the full list in the express documentation page
If you can't find the right parser for your request in Express (XML, form-data...), you need to find another library for that. For example, to parse XML data, you can use this library
You should use the parser middleware before the route declaration part (I did a test to confirm this!). The middleware can be configured right after the initialization express app.
Like other answers pointed out, bodyParser is deprecated since express 4.16.0, you should use built-in middlewares like above.
2. [CLIENT side] [Rarely] Forget to send the data along with the request
- Well, you need to send the data...
To verify whether the data has been sent with the request or not, open the Network tabs in the browser's devtools and search for your request.
- It's rare but I saw some people trying to send data in the GET request, for GET request
req.body
is undefined.
3. [SERVER & CLIENT] [Quite often] Using different Content-Type
Server and client need to use the same Content-Type to understand each other. If you send requests using
json
format, you need to usejson()
middleware. If you send a request usingurlencoded
format, you need to useurlencoded()
...There is 1 tricky case when you try to upload a file using the
form-data
format. For that, you can use multer, a middleware for handling multipart/form-data.What if you don't control the client part? I had a problem when coding the API for Instant payment notification (IPN). The general rule is to try to get information on the client part: communicate with the frontend team, go to the payment documentation page... You might need to add appropriate middleware based on the Content-Type decided by the client part.
Finally, a piece of advice for full-stack developers :)
When having a problem like this, try to use some API test software like Postman. The object is to eliminate all the noise in the client part, this will help you correctly identify the problem.
In Postman, once you have a correct result, you can use the code generation tool in the software to have corresponded code. The button </>
is on the right bar. You have a lot of options in popular languages/libraries...