Josh Gordon
Josh Gordon

Reputation: 127

ExpressJS ajax sending empty data

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.

Upvotes: 0

Views: 53

Answers (1)

eskawl
eskawl

Reputation: 637

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.

Upvotes: 1

Related Questions