Nodejs Post Request no data in console - node.js

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

Related

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

POST with Nodejs express

Unfortunately I get an empty body: {} in the request object, when I POST something to my api via Insomnia (configuration Form Form URL Encoded Header Content-Type: application/x-www-form-urlencoded):
Here is my express code:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.send("Hallo");
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
What am I doing wrong? And also what would I have to change in my code if I'd configure Insomnia to Form as JSON, Header Content-Type: application/json ?
For accessing request body use body-parser middleware and for sending the response in JSON format use res.json()
https://www.npmjs.com/package/body-parser
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.json({"message":"Hallo"}); //update here
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
available in Express v4.16.0 onwards:
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

request body undefined in node express

In node express when I try to access the post value from the form it shows request body undefined error.
Here is my code,
http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );
}).listen(9000, function() {
console.log('http://localhost:9000');
});
Please any one help me to find why the request body shows undefined.
Enable body-parser middleware first
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
If you're not using express for the web server and just plain http. Use the body module.

express router use meld to log request parameters and response

I use meld in my express project and I wanna log my api request with meld,This code below is my first try:
var meld = require('meld');
var express = require('express');
var router = express.Router();
var app = express();
var logger = {
apiAround:function(method){
//TODO:log before request
var result = method.proceed();
//TODO:log after request
return result;
}
};
meld.around(router,'get',logger.apiAround);
router.get('/',function(req,res){
//TODO:handle request
});
app.use('/',router);
but it seems not work,what is the problem?
I found the solution to this problem,actually I want to record my request param/response/response time,so this is code with middleware response-time
var responseTime = require('response-time');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(responseTime(function(req,res,time){
if(req.baseUrl.indexOf('/xxxxxx') !== -1)
{
console.log(req.body);
console.log(time);
console.log(res);
}
}));

retrieving multiple query string parameters Express 4

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var url = require('url');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json())
app.get('/', function (req, res) {
console.log(req.query);
res.send('Hello World');
})
app.listen(3000);
curl http://localhost:3000/?a=1&b=3
The console log returns { a: '1' }.
Am I missing something ?
& is a shell command that backgrounds your process so everything after & will not be passed to curl.
You need to use curl 'http://localhost:3000/?a=1&b=3' (note the quotes)

Resources