making post request issue - javascript

I'm trying to print the data received from the body yet not working. Here is my attempt ...
router.post('/api/main',(req,res) => {
if(req.error){
res.status(400).send(error.details[0].message);
return;
}
res.send(req.body.message)
})
on postmen Im making a post request like these: localhost:5000/api/main/
the body looks like these: JSON
{
"message": "hello"
}
However, im getting this response
{
"success": false,
"msg": {}
}
What am I missing

Add body parser as middleware on your post router.
Here's the proper way to set your body parser middleware.
router.use(bodyParser.urlencoded({extended: true});
router.post('/api/main', (req, res) ...)
You may also want to use bodyParser.json()

in your index file, before using any routers, add app.use(bodyParser.urlEncoded({extended: true}));

Related

How Do I Get Body From Get Request In Express?

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

Body-parser to avoid "JSON.parse(body)"

In express I can use a middleware called "body-parser" to automatically parse the incoming body.
Now that I do not have an express router to apply the middleware to, is it possible to somehow apply it to all requests in my chai test file? So that I can achieve the DRY principle.
I currently use this in every test:
it('login', done => {
request.post('http://localhost:3000', (err, res, body) => {
JSON.parse(body) // <-- I have to parse the body each time
done();
})
});
I'm assuming you are using the Request library. And if I'm understanding your question correctly, you want request to automatically parse your response body via JSON.parse.
The documentation explains how to do that under https://github.com/request/request#requestoptions-callback
json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
So your code should be something like:
request.post({url: 'http://localhost:3000', json: true}, (err, res, body) => {
console.log(res)
console.log(body)
})
Untested, but that's what I gather from reading the docs.

Send POST data with raw json with postman Express

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.

Express.js + body-parser: empty req.body from POST request

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...

Passing the params using react fetch not working

Here's the server controller (which works)
function logTheRequest(req, res) {
console.log(req.body);
res.sendStatus(200);
}
Here's the client side fetch
newCustomer() {
fetch('/customers/sign-up', {
method: 'POST',
body: 'test',
});
}
But when I console.log(req.body), all I get is { }
req.body kept coming back empty for me until I added app.use(bodyParser.json() into my server.js file. Make sure you import body-parser.
Looks like the reason is because bodyParser parses request bodies in middleware under req.body: https://github.com/expressjs/body-parser. More details on bodyParser: What does `app.use(bodyParser.json())` do?.

Categories