Reputation: 83
I have the next app.js
:
const express = require('express');
const bodyParser = require('body-parser');
const authRoutes = require('./routes/auth');
const app = express();
app.use(`$/api/auth`, authRoutes)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
module.exports = app;
And routes/auth.js
:
const express = require("express");
const router = express.Router();
router.post("/register", (req, res) =>{
res.status(200).json(req.body);
})
So, if I try to take req.body
in auth.js, I get undefined
, and if i pass any json instead of req.body, it will work fine.
Also if I'll move post
to app.js
, and it will look like this:
const express = require('express');
const bodyParser = require('body-parser');
const authRoutes = require('./routes/auth');
const app = express();
// app.use(`$/api/auth`, authRoutes)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.post("/api/auth/register", (req, res) =>{
res.status(200).json(req.body)
})
module.exports = app;
it also will work fine. What don't I see?
Upvotes: -1
Views: 51
Reputation: 83
Slebetman in comments gave the answer.
So as contents of app.use()
are middleware they depends on an order in which it disposed. Therefore I should have put lines with bodyParser
above routing middleware.
Upvotes: 0