POST req body return empty array - node.js

i have a problem when POST some data in POSTMAN my problem is during "post" method /auth/login req.body return empty array.
Postman return empty object only if i use POST method with use form-data, if i change to xxx-www-form-urlencoded whatever works fine. I wanna know why it works so
const express = require('express');
const mongoose = require('mongoose');
const app = express();
require('dotenv').config();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/static", express.static(__dirname + "/assets"))
app.post('/auth/login', (req, res) => {
res.status(200).json(req.body)
})
mongoose.connect("mongodb://localhost:27017")
.then(() => {
app.listen(port, () => {
console.log('port' + port)
})
})

I'm assuming you mean application/x-www-form-urlencoded instead of xxx-www-form-urlencoded and you mean multipart/form-data instead of form-data.
These 2 content-types are completely different encodings. When you called:
app.use(express.urlencoded({ extended: true }));
You added a middleware that can parse application/x-www-form-urlencoded, but that does not mean it automatically parses other formats too. It's only for that format, just like express.json() is only for the application/json format.

I solved this, i just created multer in my controller and it work how i wanted
const express = require('express');
const router = express.Router();
const { getUsers, createNewUser } = require('../controllers/newUser')
const path = require('path');
const multer = require('multer');
const upload = multer();
router.get('/', getUsers)
router.get('/:id', (req, res) => res.send('get single user'))
router.post('/', upload.none(), createNewUser)
module.exports = router;

Related

req.body is empty in post api (only in my laptop)

I have created this post API, when I am trying to call it from postman req.body is null always, but the same API is working fine on my friend's laptop.
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true}));
const sayHi = (req, res) => {
res.send("Hi!");
};
app.get("/", sayHi);
app.post("/add", (req, res) => {
const { a, b } = req.body;
console.log(req.body)
res.send(`The sum is: ${a + b}`);
});
app.listen(5000, () => {
console.log(`Server is running on port 5000.`);
});
this is my postman request: https://i.stack.imgur.com/d6QAZ.png
update:- I tried the same on my other laptop and it is working fine. I don't know why this is not working in my work laptop.
Hey Once try this middleware and send a proper request from POSTMAN I think this will resolve your all issues..
const express = require("express");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true}));

POST request body not available in Express middleware 'req'

I have an odd query that has really stumped me.
I have created this Express middleware:
const express = require('express')
const bodyParser = require('body-parser')
var router = express.Router()
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())
app.use(router)
router.use((req, res, next) => {
console.log(req.body)
})
router.post((req, res) => {
...
})
Whever I try to log the body in the router.post, it logs the correct body. However, when I try to log it in the router.use (as shown above), it only returns an empty object. Any thoughts of how I can get the body in middleware? Thanks!
Only isssue I see according to the official documentation is that you've to set the router to the app after declaring all the middlewares as said in the below attached image,
which means you code should be changed to
const express = require('express')
const bodyParser = require('body-parser')
var router = express.Router()
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())
router.use((req, res, next) => {
console.log(req.body)
})
router.post((req, res) => {
...
})
//setting the router as a middleware after declaring all the routes and middleware functions.
app.use(router)
References:
Express Routing
Express Router API

Nodejs bodyParser.raw on one route

I have the following in my index.js:
app.use(bodyParser.json());
But Stripe webhooks want this:
Match the raw body to content type application/json
If I change my index.js to the following:
app.use(bodyParser.raw({type: 'application/json'}));
It works fine. But all my other API routes will not work anymore. Here is my route:
router.route('/stripe-events')
.post(odoraCtrl.stripeEvents)
How can I change to the raw body for only this api route?
You can access to both at the same time by doing this:
app.use(bodyParser.json({
verify: (req, res, buf) => {
req.rawBody = buf
}
}))
Now the raw body is available on req.rawBody and the JSON parsed data is available on req.body.
Divide them into two routers '/api' and '/stripe-events' and indicate bodyParser.json() only for the first one:
stripeEvents.js
const express = require('express')
const router = express.Router()
...
router.route('/stripe-events')
.post(odoraCtrl.stripeEvents)
module.exports = router
api.js
const express = require('express')
const router = express.Router()
...
router.route('/resource1')
.post(addResource1)
router.route('/resource2')
.post(addResource2)
module.exports = router
const stripeEventsRouter = require('./routers/stripeEvents';
const apiRouter = require('./routers/api';
apiRouter.use(bodyParser.json());
stripeEventsRouter.use(bodyParser.raw({type: 'application/json'}));
app.use('/api', stripeEventsRouter);
app.use('/api', apiRouter);

How to access an API endpoint through a token using headers?

Currently I have a public api implemented, anyone can access it.
My intention is that the user now pass a token through the header so that they can access the data from the endpoints. But I don't know how to implement it in my code.
I appreciate your help!
router.get('/AllReports' , (req , res) =>{
PluginManager.reports()
.then(reports =>{
res.status(200).json({
reports
});
}).catch((err) =>{
console.error(err);
});
});
app.js
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser');
const middlewares = require('./middlewares/index').middleware;
const api = require('./api');
const app = express();
app.use(morgan('dev'));
app.use(helmet());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.json({
message: '🦄🌈✨👋🌎🌍🌏✨🌈🦄'
});
});
app.use('/api/v1', api);
app.use(middlewares);
module.exports = app;
To see a list of HTTP request headers, you can use :
console.log(JSON.stringify(req.headers));
Then you can check if token is valid and then
go on with processing.
Example
router.get('/', (req, res) => {
// header example with get
const authHeader = req.get('Authorization'); //specific header
console.log(authHeader);
// example with headers object. // headers object
console.log(req.headers);
});

Strange Response from express server

I created a simple server using expressjs and have post method but I got strange response to post article and I don't know why it happened. Could anyone mind helping me?
my expected is a JSON format.
Here is my app.js file
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
My postman. I log request body out but it is not as my expectation.
if you are sending form data(application/x-www-form-urlencoded) the you can do
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
You're sending the wrong request body via postman, your body should be JSON format, not form data
Try removing body-parser and use middlewares directly from express and set urlencoded to false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
See here urlencoded option documentation

Resources