My Code Returns Invalid Text When I Try To Do It.
app.post("/charge", (req, res) => {
console.log(req.body)
})
As the doc for req.body says:
req.body contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
The following example shows how to use body-parsing middleware to populate req.body.
By default, the body of the request is not yet read from the incoming stream and therefore it is not yet parsed into req.body either. To get it read and parsed into req.body, you have to use some appropriate middleware that will do that for you (or you could do it manually yourself, but it's generally easier to use pre-written middleware that does the job for you).
Which middleware to use depends upon the type of the data in the body (urlEncoded data, JSON data or something else).
Here's the example from the doc:
var express = require('express')
var app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/profile', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})
Related
I have a problem with express POST request,
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.post('/movie/add', (req, res) => {
console.log(req.body) // {}
//
})
can someone tell me, why after sending some data like:
{
"msg":"Hello"
}
then my req.body return me {}? He should return me an object of my msg value but instead of I have an empty array :/
thanks for any help!
You need to do two things if you want to use the request body.
1.in request header include Content-type application/json
2.in code Use middleware to parse into json. app.use(express.json());
Note use app.use(express.json()) before route declartion.
view example here
Bydefault body is undefined
app.use(express.json()); help you to defined the data
while content-type application/json allow you to pass json.if you did not include content-type application/json request.body will return define empty object { }.
I think you should use body-parser
http://expressjs.com/en/resources/middleware/body-parser.html
I am using Express and body-parser middleware to process incoming requests. On the front end, I have a form that's just a hidden input and a submit button (written in Pug):
form(notes="saveNotesForm" action=`/lessons/${lesson._id}/notes` method="POST" enctype="application/x-www-form-urlencoded")
input(type="hidden" id="hiddenNotes" name="hiddenNotes" alt="Notes Copy" value="test").notesHidden
input(type="submit" name="saveNotes" alt="Save Notes" value="Save")
On the backend, I have the Express app using body-parser:
const bodyParser = require('body-parser');
// ...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
And the route processing the incoming request:
router.post('/lessons/:lessonID/notes', lessonController.updateNotes);
// ... and in lessonController:
exports.updateNotes = async (req, res) => {
console.log('updateNotes request received');
console.log(req.body);
res.status(200).json({ status: 'success' });
}
When I try to use req.body in updateNotes, the body is an empty object, but should at least have the property hiddenNotes with the value "test". Please comment if you have any questions or think you see the problem!
[UPDATED]
This was a silly mistake, I forgot I had written a separate event handler for when this form gets submitted - it just took me posting on SO before I went through all of my code :) The event handler uses axios and looks like this:
const SaveNotesButton = $('form.saveNotes');
SaveNotesButton.on('submit', ajaxSaveNotes);
function ajaxSaveNotes(e) {
e.preventDefault();
axios
.post(this.action)
.then(res => {
console.log(res.data);
})
.catch(console.error);
}
Unfortunately, when making posts with axios, you need to include the data in an object like this, or else it won't be included in the request:
const SaveNotesButton = $('form.saveNotes');
SaveNotesButton.on('submit', ajaxSaveNotes);
function ajaxSaveNotes(e) {
e.preventDefault();
axios
.post(this.action, { notes: this.children.hiddenNotes.value }) // Data added here
.then(res => {
console.log(res.data);
})
.catch(console.error);
}
Have to tried querying your end point using Postman or something similar?
There could be one possible explanation for why your req.body is undefined. Are you sure your app.use(bodyParser.json()) and app.use(bodyParser.url... are written before your app.use('***', router) lines? If you put the body parser middleware AFTER your router middleware it essentially won't get called because middleware are called in the order they are put in app.use. So you should place your bodyParser before all your router logic. BodyParser middleware then calls all the other middleware (with the req.body populated) that come after it including all your router level middleware.
Hope it helps!
Not sure how you are defining your routes but I would expect a post route to look like the following:
const express = require('express');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post('/lessons/:lessonID/notes', (req, res) => {
// now pass the req object to your function
lessonController.updateNotes(req);
});
You need to pass the req object to your function to be able to access req.body...
Now I send data to express server as query param. But, I instead send the data to express server as payload.
How do I send payload data to express server? And how do I get the payload data from express server? Can anyone clear my doubts?
Here is my code,
// http request code
var http=new XMLHttpRequest();
http.open('post','localhost:9090/putData');
http.onload=function(){
if (this.status >=200 && this.status <300){
console.log(this.response);
}
};
var payload = {
data: 'Something'
}
http.send(payload);
// server.js
app.use(bodyParser.json({limit: '50mb'}));
app.use('/putData', function(req, res){
console.log(req.body); // empty object printed
})
What's wrong in my code.
You'll need to reference 'body' from the request object. Depending on the type, you can deserialize it with a parser. I use the npm package 'body-parser' to deserialize my objects to json. Set up the body parser in the express middleware as shown below
app.use(bodyparser.json({limit: '50mb'}));
Then you can use the req.body object in your following requests`
app.get('getBody', function(req, res){
console.log(req.body);
res.status(200);
});`
I'm attempting to store an object that my user clicks on in my server so that when the page changes, all the information from that object can be displayed fully in a profile page.
I'm unfamiliar with Angular $http but I've tried to write a call that will POST to the server, unfortunately when I scan through the req object in VScode I can't find where the object I sent is contained, so I can send it on to my function.
Controller function:
$scope.storeProfile = function(child){
$http.post('/storeTempProfile', child)
.then(function(response) {
window.location.href = 'DemoPage.html';
});
}
server.js:
app.post('/storeTempProfile', function (req, res) {
profileStorage.storeProfile(req);
});
does my app.post look right? And what property of req do I need to use the dot operator on to access my object? I can't seem to find the object data anywhere in req and that makes me thing there's something wrong with how I wrote app.post
It looks like you are using express. So in that case, you want to access the object on req.body, but this will require you use body-parser. The example on their homepage:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})
You will notice in this example that they pass the json parser into the route itself. This is only necessary if you want to have different parsers for different routes. Usually you just want to set it to all routes, which you can do by using app.use(bodyParser.json()).
I just installed the latest versions of modules. I can not get any GET or POST variables. What i do wrong?
NODE: v0.12.2
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
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))
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
http://localhost:3000/?token=devvvvv GET returns:
you posted:
{}
Thanks for answers, but problem with POST does not solved...
POST token=as123ds on http://localhost:3000/ return empty array in req.body
How can i solve this?
You are submitting parameters via the query string and attempting to access them through the request body which in this case is empty.
The token parameter will be available in request.query like so:
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.query.token, null, 2))
});
If you only plan to submit parameters in the query string you should not need to mount the body-parser middleware at all.
You should be using the req.query:
req.query
An object containing a property for each query string parameter in the route. If there is no query string, it is the empty object, {}.
api link
You are parsing JSON from the request, so the POST from client must have 'Content-Type': 'application/json' in HTTP header. If not, you'll have empty request.body at server side.
bodyparser module requires the http request's "Content-type" property equal to "application/json". It won't work for other values.
You have to check the request content type in the client, this link may help
Node (Express) request body empty
This is because bodyParser parses application/json,
application/x-www-form-encoded and multipart/form-data, and it selects
which parser to use based on the Content-Type.