I cant access body when getting expressjs request
My main server.js file
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(router);
My router.js file
const express = require("express");
const articlesContr = require("./../controllers/articlesContr.js");
const router = express.Router();
router
.get("/articles", articlesContr.handleGet)
.post("/articles", articlesContr.handlePost)
.put("/articles", articlesContr.handleUpdate)
.delete("/articles", articlesContr.handleDelete);
adminPanelContr.js
const controller = {
handleGet: (req, res) => {
const query = req._parsedUrl.query;
const parsedQuery = querystring.parse(query);
// res.send(productsDb.getItem(parsedQuery));
console.log(req)
res.send(JSON.stringify(req.body))
}
};
GET requests don't have body parameters. Ordinarily .get() handler functions don't look for them.
If you use the same handler function for GET and other (POST, PUT, PATCH, DELETE) requests, you need logic to avoid looking at the body when you get a GET.
When you send a request with a JSON body, don't forget to tell your server it's JSON by including a Content-Type: application/json HTTP header. That way you're sure express will invoke its express.json middleware to parse the body into the req.body object.
When you .get() a GET, you don't get a request body. There's gotta be some sort of doggerel poetry in there someplace.
If you use res.json(object) rather than res.send(JSON.stringify(object)) express does a good job of setting the HTTP response headers to useful values for JSON.
And, I'm sure you know this: Responding to a request with its own request body is a little strange.
Related
I'm trying to get data from a post request using express. But when I use Postman to create the resquest, the req.body is empty (console.log shows 'req {}')
I tried a couple of things and read similar questions in StackOverflow but I couldn't solve my issue.
Here are two screens of my Postman request using form-data and raw :
postman request
postman form
For the second, I also tried with the default content-type before adding application/json
Thanks for your help !
// File : router.js
import express from 'express'
const router = express.Router()
// I tried some router.get routes here and it works with no problem...
router.post('/myurl', (req, res) => {
console.log('req', req.body)
})
export default router
// File : app.js
import express from 'express';
import router from './router.js';
const app = express();
const port = 3000;
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use('/', router)
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
}
);
You need three elements of the request and server side code to match.
The Content-Type request header must specific the format you are sending the data in
The request body must be encoded to match that header (and be valid)
The server needs body parsing middleware that supports that format.
Your first screenshot shows you are POSTing raw data which is invalid JSON. It does not show what Content-Type request header you are including.
You need to make the JSON valid and ensure that you have Content-Type: application/json in the request headers.
Your second screenshot shows that you are posting multipart/form-data, but you only have middleware that parses application/json and application/x-www-form-urlencoded data.
Either change the format you are POSTing in, or add suitable middleware.
Note also that the Content-Type of the individual parts is wrong. example is not valid JSON (100 is valid JSON but you probably don't want it to be treated as such).
I'm just trying to pass the simplest data possible (at the moment, for test purposes) from client to server with a POST request, but I keep getting empty or undefined logs on req.body.
Server:
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/sandbox", {useNewUrlParser: true});
app.get("/", function(req, res){
res.render("home", {});
})
app.post("/filter", function(req, res){
console.log(req.body);
res.redirect("/");
})
app.listen(3000, function() {
console.log("Server started on port 3000");
});
Client (version 1):
var yourdata = { "name": "The pertinent data"};
console.log(document.body)
$.ajax({
url : "/filter",
type: "POST",
dataType:'text',
data : yourdata,
contentType: "application/json",
});
Client (version 2):
var payload = {data: "The pertinent data"};
var req = new XMLHttpRequest();
req.open('POST', '/filter' , true);
req.send(JSON.stringify(payload))
I added both attempts at a code client-side, but I'm happy with whichever method works. Ideally I'll eventually tap into the payload or data with req.body.payload or something, but at the moment that's just giving me an undefined.
I've looked into quite a few similar posts and usually they were missing the "app.use(bodyParser.urlencoded({extended: true}));" or "app.use(bodyParser.json());" I've tried adding and removing those, changing from true to false, still empty.
The console.log(document.body) on the client script does work, giving me the expected body on the browser console, and the server route is working too, eventually redirecting to home.
I can't see how the issue is something I'm doing wrong on the client side, but oddly enough, if I create a form, with an action to that route, and submit, it seems to send the req.body normally. E.g.:
<form class="form" action="/filter" method="post">
<input name="newName" placeholder="Name">
<button type="submit">Submit</button>
</form>
That does indeed log a JSON object e.g.: { newName: 'John'}
In case it might be relevant, the HTML is the simplest one possible, almost empty, only really doing the pertinent links.
Thanks all in advance!
You need three things:
A request body encoded in some data format
A content-type request header which says which data format you are using
Body parsing middleware that can process that data format
When you submit a form, with no enctype attribute, it will submit the data in URL encoded format with the right content type. This matches the body parsing middleware you have (bodyParser.urlencoded({extended: true})).
1, 2, and 3 are all good.
Note that it does not create a JSON object. The client produces URL encoded data. The server parses that into a JavaScript object. There is no JSON.
Client (version 1):
Here you are passing an object to jQuery so it will URL encode the data in it and would normally set the correct content type.
It is failing because you have contentType: "application/json",.
Since you are falsely claiming that you are sending JSON, bodyParser.urlencoded ignores it.
If you had a JSON body parser in place, it would error because the data is not JSON.
1 and 3 are good, but 2 is a lie.
Remove the contentType property.
Client (version 2):
Now you are JSON encoding the data, but you aren't setting the content type request header, and you don't have body parsing middleware that can handle JSON.
3 is bad, and either 1 or 2 is too.
For the server-side part of your application, you need something that moves the body of the request out of the request string itself to a clear, easy-to-read, and use variable. The express json() method (middleware) does that exactly.
Use the express JSON parser middleware as follows:
app.use(express.json())
Code:
const express = require("express");
// const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
app.use(express.json()); // 👈 here
// ... the rest of your code
Just few notes about the middleware you're using
app.use(bodyParser.urlencoded({extended: true}));
We usually use this middleware to parse the HTML forms data, in other words, it's just like the express middleware express.json(), but the difference here is that it parses the requests which have the content type of HTML forms, while the express.json() converts the ones which have the content-type of application/json.
If you're using express v +4, you don't need the bodyParser package, express has the .urlencoded() and the .json() methods built into the express package itself, you can use them just as express.json() and express.urlencoded().
Tip, you can have both middlewares, the JSON parser, and the HTML form content type parser, when the server receives a content-type JSON, the express.json() middleware will parse the request body, and if the server receives an HTML form content-type the urlencoded middleware will fire:
code example:
const express = require("express");
// const bodyParser = require("body-parser"); ❌ not needed
const mongoose = require("mongoose");
const app = express();
app.use(express.json()); // 👈 here
app.use(express.urlencoded({ extended: true })) // 👈 here
// ... the rest of your code
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.json())
app.use(cors());
app.post('/', (req,res) => {
console.log(req.body);
res.send('received')
})
app.listen(5000, console.log('Server is running on port 5000'));
I am trying to send data to the back-end but always getting undefined
I tried to you a parser but seems like just wrapping void into an object
Posting as answer from my comment.
In the second image in postman you need to change the type dropdown from text to JSON, express.json() only parses the body when the header Content-type is set to "application/JSON" and changing that dropdown will automatically include that header.
Here are the docs if it helps explain why you get the empty object in the second image
I am creating a PUT method to update a given set of data however in my update function, req.body is undefined.
controller.js
async function reviewExists(req, res, next) {
const message = { error: `Review cannot be found.` };
const { reviewId } = req.params;
if (!reviewId) return next(message);
let review = await ReviewsService.getReviewById(reviewId);
if (!review) {
return res.status(404).json(message);
}
res.locals.review = review;
next();
}
async function update(req, res, next) {
console.log(req.body);
const knexInstance = req.app.get('db');
const {
review: { review_id: reviewId, ...review },
} = res.locals;
const updatedReview = { ...review, ...req.body.data };
const newReview = await ReviewsService.updateReview(
reviewId,
updatedReview,
knexInstance
);
res.json({ data: newReview });
}
service.js
const getReviewById = (reviewId) =>
knex('reviews').select('*').where({ review_id: reviewId }).first();
const updateReview = (reviewId, updatedReview) =>
knex('reviews')
.select('*')
.where({ review_id: reviewId })
.update(updatedReview, '*');
How it should look:
"data": {
"review_id": 1,
"content": "New content...",
"score": 3,
"created_at": "2021-02-23T20:48:13.315Z",
"updated_at": "2021-02-23T20:48:13.315Z",
"critic_id": 1,
"movie_id": 1,
"critic": {
"critic_id": 1,
"preferred_name": "Chana",
"surname": "Gibson",
"organization_name": "Film Frenzy",
"created_at": "2021-02-23T20:48:13.308Z",
"updated_at": "2021-02-23T20:48:13.308Z"
}
The first function where I check if a review exists work with my delete method. Am I missing something in one of these functions that would make req.body undefined?
Nobody in the other answers is really explaining the "why" here. By default req.body is undefined or empty and the Express engine does not read the body of the incoming request.
So, if you want to know what's in the body of the request and, even further, if you want it read and then parsed into req.body so you can directly access it there, then you need to install the appropriate middleware that will see what type of request it is and if that's the type of request that has a body (like a POST or a PUT) and then it will look at the incoming content-type and see if it's a content-type that it knows how to parse, then that middleware will read the body of the request, parse it and put the parsed results into req.body so it's there when your request handler gets called. If you don't have this type of middleware installed, then req.body will be undefined or empty.
Express has middleware like this built in for several content-types. You can read about them here in the Express doc. There is middleware for the following content types:
express.json(...) for "application/json"
express.raw(...) reads the body into a Buffer for you to parse yourself
express.text(...) for "text/plain" - reads the body into a string
express.urlencoded(...) for "application/x-www-form-urlencoded"
So, you will need some middleware to parse your specific content so you can access it in req.body. You don't say exactly data type you're using, but from your data expectations, I would guess that perhaps it's JSON. For that, you would place this:
app.use(express.json());
Somewhere before your PUT request handler. If your data format is something else, then you could use one of the other built-in middleware options.
Note, for other data types, such as file uploads and such, there are whole modules such as multer for reading and parsing those data types into properties that your request handler can offer.
You should use a body parser. Basically, Express can't know how to parse the incoming data the users throw at it, so you need to parse the data for it. Luckily, there are a few body parsers (and for quite some time body parsers for JSON and UrlEncoded (not sure if there are any others) are built into Express itself). The way you do that is you add a middleware in your express app like that:
const app = express();
...
app.use(express.json({
type: "*/*" // optional, only if you want to be sure that everything is parsed as JSON. Wouldn't recommend
}));
...
// the rest of the express app
Make sure that you have body-parser middleware installed, which extract the body of request stream and exposes it on req.body (source)
npm install body-parser --save
Here's how express server definitions would look like:
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())
To get access to request body, you need to use express.json(). Make sure before using router, just wire your app.use(express.json()) that should make the request object available.
I'm currently using express to handle a POST request, but when I POST using node-fetch, I send a body and then I console.log() the body received in express (server code). I get an empty object. Not sure why this is happening, I will include my code here below.
Server Code
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
// GET method route
app.get('/api/getHeartCount', function (req, res) {
res.send('GET request')
});
// POST method route
app.post('/api/sendHeart', function (req, res) {
res.sendStatus(200);
let fBody = JSON.stringify(req.body);
console.log("Got body: " + fBody); // When this is run, I get this in the console: Got body: {}
});
app.listen(3000);
POST request code
const fetch = require("node-fetch");
(async () => {
const body = { heartCount: 1 };
const response = await fetch('http://localhost:3000/api/sendHeart', {
method: "post",
body: JSON.stringify(body)
});
const res = await response.text();
console.log(res);
})();
you used the wrong bodyParser
You must use the bodyParser.json() middleware like so in order to be able to parse json and access the body at req.body
// this snippet will enable bodyParser application wide
app.use(bodyParser.json())
// you can also enable bodyParser for a set of routes if you don't need it globally like so
app.post('/..', bodyParser.json())
// or just for a set of routes
router.use(bodyParser.json()
bodyParser.json([options])
Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).
from : https://www.npmjs.com/package/body-parser#bodyparserjsonoptions
NOTE : don't forget to add the Content-Type: application/json to your requests if you are sending a json type body
UPDATE : as #ifaruki said, express is shipped with a built-in json bodyParser accessible via express.json() from : https://expressjs.com/en/api.html#express.json
You should parse the body of your request
app.use(express.json());
With the newest express version you dont need body-parser