Express js bodyparser post req.body not working? - javascript

I try to build an api with express js post request. I use body-parser for req.body . But after sending post request i couldn't get any message still loading then show timeout. where is my problem please take a look my code.
I am testing it from postman and use on header content-type application/json.
const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config/config.js').get(process.env.NODE_ENV);
const mongoose = require('mongoose');
const app = express();
mongoose.connect(config.DATABASE)
const {Book} = require('./models/book')
app.use(bodyParser.json())
// Post Book
app.post('api/book', (req,res)=>{
let book = new Book(req.body)
book.save((err, doc)=>{
if(err) return res.status(400).send(err);
res.status(200).json({
post:true,
bookId: doc._id
})
})
})
Now error show- cannot post /api/book
but when i try with this below code its working--
const book = new Book({ name: 'Zildjian' });
book.save().then(() => console.log('data save'));

Change your route from api/book to /api/book - add a leading /.
Also, it looks like it might be timing out as it can't get passed your cookie-parser middleware.
You have passed the function:
app.use(cookieParser)
...but you need to invoke it:
app.use(cookieParser())
You will also need to import it:
const cookieParser = require('cookie-parser')
...or just remove it completely if you don't need it.
I hope this helps.

Related

Get buffer from post body in Expressjs

I am making an express application that handles post data. Because the request body could be any content type and/or binary, I would like req.body to be a Buffer. So what should I use to get a Buffer that represents the request body? Here is my code:
import express from "express";
const app = express();
app.get("/", (req, res) => {
// Get request body as buffer
// Do something with the buffer
});
body-parser can help achieve this, code example would be as,
import express from 'express';
const bodyParser = require('body-parser');
const app = express();
const options = {
type: 'application/octet-stream',
};
app.use(bodyParser.raw(options));
app.get('/', (req, res) => {
const bufferObject = req.body; // Get request body as buffer
// Do something with the buffer
});
See more details about Raw body parser and default options needs to be supplied - bodyParser.raw([options])

Can't send data through axios and node back-end

I am trying to access the expression passed from the backend to the frontend through axios.
Producer side:
const axios = require('axios');
const URL = "http://localhost:5000/"
let n1 = 3
let n2 = 5
let sum = n1+n2;
axios.post(URL, JSON.stringify({
expression: sum,
}))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
and on the consumer side:
const express = require('express')
const app = express()
app.post('/', (req, res) => {
console.log(req.body);
})
app.listen(5000, () => console.log())
Ultimately, I would like to have the consumer side log "8"
You don't need to convert to JSON, axios serves JSON natively.
Add to the server:
app.use(express.json())
Just send you data:
axios.post(URL, { expression: sum, })
.then(console.log)
.catch(console.err)
From the "express" documentation:
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 body-parser and multer.
Try including this before you try to register the endpoint:
const bodyParser = require('body-parser')
app.use(bodyParser.json())
You can also use express.json() and drop the 'body-parser' dependency:
// const bodyParser = require('body-parser')
app.use(express.json())
Axios have some security measures as well, you should put your IP address in
const URL = "http://localhost:5000/"

express.js get method cannot get req.body value

I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine

Javascript express mongodb server not getting data from post request

I am trying to set up a very simple javascript server however I cant even properly get the data from a post request!
Here is what I am doing. I have annotated what works and what doesn't. Essentially everything except for the post request works perfectly. Unfortunately the body of the request is always empty resulting in garbage information.
const MongoClient = require('mongodb').MongoClient;
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }))
const mongoUrl = '<DBAddress Goes Here>';
MongoClient.connect(mongoUrl, (err, mongoDb) => {
if(!err) {
db = mongoDb;
console.log("Connected correctly to server");//This always happen successfully
}
});
app.listen(80);
app.get('/test', function(req, res) {
res.json({ data1: 11, data2: 4, data3: 9 }); //This always works!
});
app.post('/update', function(req, res) {
const params = req.body;
console.log(req.body);//Empty
console.log("Parameters");
const newReport = {
id: params.id,
data: params.data
};
console.log(newReport);//Nothing is put in here
});
I am testing this post request in Postman with website.com/update as the address and the proper fields in the body part of the post.
You need to parse request body in order to get the body in req.body.
As you are already using body-parser package just add the following line after your urlEncoded middleware. and remember the order of middleware matters in the express.
app.use(bodyParser.json());
add above line right after this
app.use(bodyParser.urlencoded({ extended: false }))
And make sure that you are sending data in the JSON format as by default postman send data in plain format

Express body-parser req.body with formdata is empty object

Somehow my req.body is always empty, maybe you have an idea:
here is my server code:
const Express = require('express');
const bodyParser = require('body-parser');
const app = new Express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/save', (req, res) => {
console.log(req.body) // => {}
res.send(req.body);
});
const env = process.env.NODE_ENV || 'production';
app.listen(3000, err => {
if (err) { return console.error(err); }
console.info(`Server running on http://localhost:${port} [${env}]`);
});
When I try to send formdata with javascript the req.body is empty:
const data = new FormData(document.querySelector('form'));
console.log(data); // seems empty already??? FormData{}??
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/save');
xhr.send(data);
Same with postman:
I don’t understand this…
Sending x-www-form-urlencoded with postman or raw (application/json) works in postman. But sending the same headers with Formdata in javascript will still result in an empty object…
To log every field in formData
let myForm = document.getElementById('myForm');
formData = new FormData(myForm);
for (let [key, value] of formData.entries()) {
console.log(key, value);
}
Fiddle - https://jsfiddle.net/thesumit67/j4znhxa5/1/
To handle it via express use multer.
Here is an example -
https://www.npmjs.com/package/multer
Make sure to add enctype="multipart/form-data" on form element. Otherwise Multer will ignore it.
let multer = require('multer');
let upload = multer();
app.post('/save', upload.fields([]), (req, res) => {
console.log( req.body );
console.log( req.files );
res.sendStatus(200);
});
body-parser is deprecated and isn't a part of Express anymore.
Also, body-parser does not provide the functionality to parse form-data post data.
From the body-parser repository description:
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
busboy and
connect-busboy
multiparty and
connect-multiparty
formidable
multer
From what I understand, the problem may be in the HTML form.
<form action="" method="POST">
<input type="text" name="foo[bar]">
<button>Submit</button>
</form>
Then in the server code it may look something like this.
app.post('/save', (req, res) => {
console.log(req.body.foo) // => {}
res.send(req.body.foo);
});
Again, this post is older so you've probably already fixed it.
I had this same problem, I was using the fetch api, sending form data to an node.js/express backend. The problem was that I had set enctype='multipart/form-data' on the form and I was also setting Content-type: multipart/form-data in the fetch Headers.
Removing the Content-type from the Headers got everything to work.
I got the solution from here => https://github.com/expressjs/multer/issues/411
Express and body parser Version :
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
app.js:
const express = require('express');
var bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use( bodyParser.json());
const baseUrl = '/api/v1/tours';
app.post(baseUrl, (req, res)=>{
console.log(req.body);
res.send('Done');
})
//starting server
const port = 3000;
app.listen(port, ()=>{
console.log(`app running on port ${port}...`);
});
To send raw data please select JSON from the list

Categories

Resources