ExpressJS ajax sending empty data - javascript

I need to send JSON to my server, but the POST requests are appearing with an empty body. Here is my typescript on the front end:
function sendData() : void {
console.log("Sending data...");
var name_ : string = (document.getElementById("name") as HTMLInputElement).value;
var id_ : string = (document.getElementById("series") as HTMLInputElement).value;
var toSend = new FormData();
toSend.append("name",name_);
toSend.append("id",id_);
var request = new XMLHttpRequest();
request.open("POST", "/add");
request.send(toSend);
}
My server has this code: I've omitted the file paths.
var Express = require('express');
var BodyParser = require('body-parser');
var Multer = require('multer');
var app = Express();
var upload = Multer();
app.use(Express.static("/public"));
app.use(BodyParser.urlencoded({extended:true}));
app.use(BodyParser.json());
app.get('/public/dataAjax.js', function(req,res){
res.sendFile("C:\\<omitted>\\dataAjax.js");
})
app.get('/', function(req,res) {
res.sendFile("C:\\<omitted>\\index.html");
});
app.post('/add', function(req,res) {
console.log("Received:");
console.log(req);
res.status(201).json(req.body.name);
});
app.listen(8000, () => console.log("Running on port 8000!"));
My problem appears to be entirely server side, as I've used flask in the past and this code worked fine. My focus here is using node with expressjs.

This only parses a request with a Content-Type of application/x-www-form-urlencoded. See docs of body parser.
app.use(BodyParser.urlencoded({extended:true}));
FormData sends the request with Content-Type set as multipart/form-data.
As your bodyparser can't parse such content type, you should try to send the data either as application/json or application/x-www-form-urlencoded.
See MDN docs of FormData.
You can use jquery's serialize method to get the urlencoded string.

Related

Post request body empty - XMLHttpRequest to Express server

I am trying to access a body from a post request sent using XMLHttpRequest to an express server. However the body of the request is empty and I cannot seem to understand why that is.
I have included a body-parser in the express app, and I have tried to replicate some code from SO answers. But I still get it wrong somehow.
<script>
const Http = new XMLHttpRequest();
Http.open('post', 'localhost:3000');
Http.send("sending something!");// this resolves to {} on the backend?
Http.onload = function() {
alert(Http.response);
};
</script>
This is how I try to handle it on my express server
const express = require("express");
let app = express()
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.post("/post", (req, res) => {
console.log("inside of post");
console.log(req.body);
})
app.listen(3000)
This is the logs
inside of post
{}
I expect the console.log() to print "sending something!" that I try to send with the request with Http.send("sending something!");.
You have specified the body-parser to parse the body as url-encoded format which would work if you pass data like this:
Http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Http.send("param1=value1&param2=value2");
/* console output:
{ param1: 'value1', param2: 'value2' }
*/
In your case, the data being passed is simple string, which the backend interprets as empty JSON {} as it is unable to parse.
For it to work try setting the format of data as follows
<script>
const Http = new XMLHttpRequest();
Http.open('post', 'localhost:3000');
Http.setRequestHeader("Content-Type", "text/plain");
Http.send("sending something!");
Http.onload = function() {
alert(Http.response);
};
</script>
And in express server:
const express = require("express");
let app = express();
const bodyParser = require("body-parser");
// app.use(
// bodyParser.urlencoded({
// extended: true
// })
// );
app.use(bodyParser.text({ type: "text/plain" })); // use this instead
app.post("/post", (req, res) => {
console.log("inside of post");
console.log(req.body);
return req.body;
});
app.listen(3000);
Then you might be able to read the message "sending something!" in the backend.
Just make sure you are setting the right contentType header in XMLHttpRequest while sending and you use same type while parsing in the backend as well.
For more info on bodyParsers refer this doc

How to pass data from client side Javascript to node.js using XMLHttpRequest?

I have HTML inputs in my index.html file.
<input type="text" id="handle" >
<input type="text" id="message" >
<button id="send">send</button>
When I fill up data and click send, I want to send them to my node script where I can do something with passed data.
My index.html's script:
$("#send").on("click", function() {
var message = $("#message").val();
var handle = $("#handle").val();
var xhr = new XMLHttpRequest();
var data = {
param1: handle,
param2: message
};
xhr.open('POST', '/data');
xhr.onload = function(data) {
console.log('loaded', this.responseText);
};
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
});
And how I have tried to recieve data in my serverside test.js file.
app.post('/data', function(req, res){
var obj = {};
console.log('body: ' + req.body);
res.send(req.body);
});
In this case, the output shows: body: undefined
How can I send the data from my client side pages to server side so that I can use them to perform my other operations?
You just need to use a JSON body parser in Express like so:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(express.static('./'));
/* Parse JSON data using body parser. */
app.use(bodyParser.json());
app.post('/data', function(req, res){
console.log('body: ', req.body);
res.send(req.body);
});
app.listen(port);
Just do an npm install for this module if not already present:
npm install body-parser

Sending JSON data to server with Expressjs

I have an html form that has several fields which I package in a JSON, and I need to send this to a server. I have the following code on the front end:
var data = {
//data here
};
var xhr = new XMLHttpRequest();
xhr.open("POST","localhost:8000/add",true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);
And then on the server, I have this code to receive it:
app.post('/add', function(req,res) {
console.log(req.body.name);
res.json(req.body.name);
});
It sends nothing; what do I need to do to get it to send the JSON?
You need to use body-parser to get values in req.body
From npm documents
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())
You are not handling the response of post request,and also make sure you are using body parser at backend. So you front end code should be like this:
var data = {name:"xyz"};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST","localhost:8000/add",true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.log(data);
} else {
console.log(data);
}
}
xhr.send(json);
And your server side code should be coded like :
var express = require('express')
var bodyParser = require('body-parser')
var app = express();
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/add', function(req,res) {
console.log(req.body.name);
res.status(201).json(req.body.name);
});
I tested it with this code and it success with me:
Client code same as your code.
Server Code:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/add', function(req,res) {
console.log(req.body.name);
res.json(req.body.name);
});

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