Express - `req.body` is always empty - node.js

I am trying to build a full stack(MERN) application. When I'm sending a request to my Express server with a JSON, I always see my req.body is empty. I can nowhere see my JSON inside my request.
I have tried using only app.use(bodyParser.json()) and app.use(bodyParser.urlencoded({ extended: true }));,but no change.
index.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for encoded bodies
console.log("App");
require("./schema/data");
require("./routes/home_routes")(app);
require("./routes/table_routes")(app);
require("./routes/utility_routes")(app);
utility_routes.js
const mongoose = require("mongoose");
const Data = mongoose.model("data");
module.exports = app => {
app.get("/api/search_member", (req, res) => {
console.log("Utility", req);
console.log("Req Done");
// const search = await Data.findById({ member_id: req.body.member_id });
// console.log(search);
});
};
request.body
[0] body: {},
[0] route:
[0] Route {
[0] path: '/api/search_member',
[0] stack: [ [Layer] ],
[0] methods: { get: true } } }
request from client
onSearch = async value => {
console.log(value);
if (value) {
const searchData = await axios.get("/api/search_member", { value });
console.log(searchData);
}
};

You are making a GET request. GET request do not send body. To get req.body, make POST request to server.
Firstly:-
const searchData = await axios.post("/api/search_member", { value });
And Secondly,
app.POST("/api/search_member", async (req, res) => {
console.log("Utility", req);
console.log("Req Done");
});

This is what I use to accept the json
var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json());
app.use(cookieParser());
And in the request set headers like this.
Content-Type : application/json
Both the axios and http libraries from angular works with this settings for me.

Related

How can I proxy form data using http-proxy-middleware?

I created a proxy on firebase using http-proxy-middleware.
It works on GET requests but does not pass the data I send via body in POST requests. I did some research and added the "onProxyReq" method to the options. This way it works when I send json body, but not when I send form data.
const functions = require("firebase-functions");
const express = require("express");
var bodyParser = require("body-parser");
const {
createProxyMiddleware,
fixRequestBody,
} = require("http-proxy-middleware");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var restream = function (proxyReq, req, res, options) {
if (req.body) {
let bodyData = JSON.stringify(req.body);
proxyReq.setHeader("Content-Type", "application/json");
proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
};
app.use(
"/",
createProxyMiddleware({
target: "http://IPADDRESS:8080/api",
changeOrigin: true,
onProxyReq: restream,
bodyParser: false,
})
);
exports.api = functions.https.onRequest(app);
This code works with json body.
Changing "application/json" to "multipart/form-data" doesn't work.
All I want is to redirect the JWT token in the header and the FormData in the body.
What should be the best way for this?

request body is empty in post method node js server

Login.js - react component.
I printed the JSON.stringify(credentials) object and it is valid but when i print the req.body in the server it is empty.
//sending a post request to the server with the username and password inserted by the user.
async function loginUser(credentials) {
console.log(JSON.stringify(credentials));
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(response => {
console.log(response);
})
};
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
you have to use a middleware to parse the json body in the post request,
you have not used bodyParser.json() as middleware
below is your updated code
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})

Empy req.body in NodeJs, Express

I'm trying to send a json to my nodeJs app through POST Method in body.
For that I'm using POSTMAN to create the request, with the proper consnt-type header and body JSON Rows. Tho the message back is "OK" in console the req.body is {} empty.
Would you have an idea what's wrong in my code?
const bodyParser = require('body-parser');
const { Client } = require('pg');
const express = require('express');
const app = express();
// create application/json parser
const jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded({ extended: false })
const hostname = '127.0.0.1';
const port = 3000;
const dbSchema = 'public';
const client = new Client({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: '123123',
port: 5432,
});
client.connect();
/* =========== Some Initialize staff =============== */
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
app.use(bodyParser.urlencoded({
extended: true
}));
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
/* =========== FROM HERE =============== */
app.post('/post-test', urlencodedParser, (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});
app.get('/',(req,res)=>{
res.status(200).send('Get Ready for something awesome!\n');
});
enter image description here
You should use app.use(bodyParser.json());, in your code const jsonParser = bodyParser.json() this is not used.
Update: Or you can apply jsonParser middleware directly to the post route:
app.post("/post-test", jsonParser, (req, res) => {
console.log("Got body:", req.body);
res.json({ ...req.body });
});
Can't figure what is happening so, I am posting the code that works for me -
let express = require('express');
let app = express();
const authorRoute = express.Router();
authorRoute.use(express.json());
authorRoute.use(express.urlencoded({extended:true}));
authorRoute.post('/post-test', async (req, res) => {//req.body});
app.use(authorRoute);
Also, make sure to test with a well-formed JSON.
version "express": "^4.17.1",

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);
});

Nodejs Post Request no data in console

Not able to get any data in the following post request , any suggestions ?
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlEncodedParser = bodyParser.urlencoded({extended:false});
var app = express();
// add Service
app.post('/api/service/addService',urlEncodedParser, (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});
Will you try this
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
after that write your code -
app.post('/api/service/addService', (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});

Resources