I'm trying to log all the data and then return it as a response.
app.post('/data', (req, res) => {
const data = req.body
console.log(data)
return res.json({
data
})
})
I'm sending data with Postman. In the Body tab I have "raw" selected and "JSON (application/json)". Headers tab is Content-Type application/json. I'm sending this:
{
"aa": 23
}
When I click send button all I get is an empty object and the data variable is undefined in my console.log. How to fix it? I double checked everything. It should work, but it doesn't.
It seems like you're passing an invalid value to res.JSON(). Try:
return res.json(data);
Alright, I found the solution.
"As body-parser module is used to parse the body and urls, it should be called before any call to 'req.body...'."
So I did this:
import bodyParser from 'body-parser'
const app = express()
app.use(bodyParser.urlencoded())
app.use(bodyParser.json())
app.post('/data', (req, res) => {
const data = req.body
console.log(data)
return res.json({
data
})
})
And now it works fine.
Related
I have been trying to use post request to insert data to the mongodb using mongoose, however I see that req.body is being shown as undefined. document is getting inserted in database, however only default object id is getting inserted.
This is how I send request to Postman
{
name:"wewe",
price:43}
//Post.js
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/tutorialkart");
const productSchema = mongoose.Schema({
name: String,
price: Number
});
module.exports = mongoose.model('Groduct', productSchema);
//app.js
var express = require('express')
var bodyParser = require('body-parser')
var Post = require('./Post')
var app = express()
app.use(bodyParser.json())
app.post('/api/posts', function (req, res, next) {
var post = new Post({
name: req.body.name,
price: req.body.price
})
console.log("Log "+post.name );
post.save(function (err, post) {
if (err) { return next(err) }
res.json(201, post)
})
})
app.listen(3000, function () {
console.log('Server listening on', 3000)
})
There are two issues with your request in Postman (you removed the screenshot which showed these issues):
it's not formatted as proper JSON, but as a Javascript object
you're sending it as text/plain, not application/json
This is how I send request to Postman
{ name:"wewe", price:43}
One of two things is happening:
Either you aren't setting a Content-Type header in the request so the JSON parsing middleware you set up isn't being triggered or
You have, but since your JSON is invalid, it is failing to parse it.
You have to write valid JSON!
You can test your JSON with JSON Lint.
In particular, property names in JSON must be strings and cannot be identifiers. Strings in JSON must be delimited with " characters.
Your screenshot is not visible/trouble opening the screenshot. You need to be more specific with your question.
I think mongoose.connect("mongodb://localhost/tutorialkart"); here you need to specify the PORT localhost:27017
Make sure you defined the names "name" and "price" in your HTML/EJS and setting their value as the data you are trying to insert into database.
Use new before mongoose.model, mongoose.Schema
app.use(bodyParser.json()) should be app.use(bodyParser.urlencoded({ extended: true }));
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
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)
})
I am trying to test my newly written api to send messages. It catches a message and sends it to a database. I am using https://apitester.com/ to test it. When I try to read req.body, I get undefined.
SERVER
app.route('/message')
.post(createMessage);
var createMessage = (req, res) => {
console.log(req.body)
var newMessage = new Message(req.body)
mlab.insertDocument({database:'databasename', collectionName:'collectionname', documents:newMessage.getCreatePack()})
.then(result => {
res.json(result)
})
}
When I try to log(req.body), I get undefined
This is the request data. Any help is appreciated
As it turns out, I need body parsing middleware, such as body-parser.
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...