When the request from postman initiated with the json as given below, I get hello undefined as response.
request json
{
"name":"test"
}
my middleware
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.get('/hello', (req, res)=>{
return res.send("hello");
});
app.post('/hello', (req, res)=>{
console.log(req.body);
return res.send(`hello ${req.body.name}`);
})
app.listen(8000, () => console.log('listening on port 8000'));
started the server with following command
npx babel-node src/server.js
Since express 4.16.0 you can use app.use(express.json()); to get the json data from request,in your case it would be.You don't require to use bodyparser and all.
const app = express();
app.use(bodyParser.json()); // remove this
app.use(express.json())// add this line
Actually issue is not with the code. The Postman client making the request didn't mark it as application/json type request. Once I rectified it, it just worked as expected.
use bodyParser as meddleware
const app = express();
app.use(bodyParser.urlencoded({ extended: true })); //add this
app.use(bodyParser.json());
also
app.post('/hello', (req, res)=>{
console.log(req.body);
name.push(req.body.name) // add this if you store in array
return res.send(`hello ${req.body.name}`);
})
Related
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}));
I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?
By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().
You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());
When I put app.use(bodyParser.json()); below app.use('/api', require('./routes/api'))
req.body returns undefined. But if I put app.use(bodyParser.json()); above app.use('/api', require('./routes/api')); it returns correctly. So the question is why?
Here is my code:
index.js file
const express = require('express');
const app = express();
const bodyParser= require('body-parser');
app.use(bodyParser.json());
app.use('/api', require('./routes/api'));
app.listen(process.env.port || 3000, function(){
console.log('You are listening to port 3000');
});
api.js file
const express= require('express');
const router= express.Router();
router.get('/ninjas', function(req, res){
res.send({type: 'GET'});
});
router.post('/ninjas', function(req, res){
console.log(req.body);
res.send({type: 'POST'});
});
router.put('/ninjas/:id', function(req, res){
res.send({type: 'PUT'});
});
router.delete('/ninjas/:id', function(req, res){
res.send({type: 'DELETE'});
});
module.exports =router;
Thanks in advance!
We need body-parser middleware to read from req.body,
In Javascript code executes line by line (for non IO operations).
So when you place app.use(bodyParser.json()) after requiring your router file logic, body-parser is not invoked and plugged, so you need to invoke it before any other logic, so that you can read from the request.
Bodyparser is a middleware which should run everytime when a route is accessed.
A middleware (like bodyparser) is written like this
const middleware = (req, res, next) => {
//some code here
next();
}
The next function starts the execution of another middleware function
So when you use the bodyparser middleware after the routes req.body will not be initialized because the bodyparser middleware never ran for the route and the response ends with the res.send().
But if you use the bodyparser middleware before initializing the routes the bodyparser middleware will always run.
You can see more examples on middleware in the expressjs docs
https://expressjs.com/en/guide/using-middleware.html
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
I actually have a very tiny app in node.js with Express, and I can't access to req.body.
This is my app.js code:
var express = require('express'),
middleware = require('./middleware'),
mysql = require('mysql'),
app = express();
app.use(middleware.authenticate);
app.use(middleware.getScope);
app.listen(3000);
module.exports = app;
And the file with the middlewares:
var bcrypt = require('bcrypt'),
mysql = require('mysql');
function authenticate(req, res, next){
console.log(req.body);
next();
}
function getScope(req, res, next){
console.log(req.body);
next();
}
module.exports.authenticate = authenticate;
module.exports.getScope = getScope;
In all cases req.body is undefined.
I'm sending data throw Postman with x-www-form-urlencoded protocol, in this case is a must.
Thanks!!
You need to add body-parser to express:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
Check Request here http://expressjs.com/en/api.html
And perhaps a POST route could help too:
app.post('/', function (req, res, next) {
console.log(req.body);
res.json(req.body);
});