TLF
TLF

Reputation: 85

Access AJAX POST data with Node.js/Express

I'm building a web application that uses Node.js/Express for the backend.

In my front end, I am sending an AJAX request to the server through Javascript that looks likes this:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8080", true);
xhttp.send("sometexthere");

This goes to my Node.js server. So far, I have been able to respond to these requests perfectly fine. However, now I want to access the "sometexthere" on my server.

var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//some other stuff 

app.post('/', function(req, res) {
      //How do I access the text sent in xhttp.send()
}

I've tried using req.body and req.query. However, all of those values show up empty. How do I send text with xhttp.send() and then get it from the req object in Express?

Thanks!

Upvotes: 1

Views: 519

Answers (2)

Nija
Nija

Reputation: 188

Try setting header to your AJAX request

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

then you will able to read in req.body

Upvotes: 1

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

Try this sending it like this

xhttp.send("foo=bar&lorem=ipsum");

Upvotes: 0

Related Questions