Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest GET params undefined in request nodejs api

Tags:

I'm trying to pass params via XMLHttpRequest and get 'undefined'-

Client :

var xj = new XMLHttpRequest();
var params = JSON.stringify({
    PreviousTab: "cnn.com",
    CurrentTab: "bbc.com"
});

xj.open("GET", "http://localhost:8080/api/traceTabs", true);
xj.setRequestHeader("Content-Type", "application/json");
xj.setRequestHeader ("Accept", "application/json");

xj.send(params);

Server (Node.js):

app.get('/api/traceTabs', function (req, res) {
   console.log('change url from ' + req.body.PreviousTab +
   ' to ' + req.body.CurrentTab); // return 'undefined'
         });

server.js Config (Node.js):

var express        = require('express');
var app            = express();
var bodyParser     = require('body-parser');
var methodOverride = require('method-override');

var port = process.env.PORT || 8080;     
app.use(bodyParser.json()); 
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
app.use(bodyParser.urlencoded({ extended: true })); 

app.use(methodOverride('X-HTTP-Method-Override')); 
app.use(express.static(__dirname + '/public')); 

require('./app/routes')(app); 

app.listen(port);   
console.log('Listen to port ' + port);          
exports = module.exports = app;                         

All the options that I've tried to get the params return 'undefined':

req.body.PreviousTab / req.param('PreviousTab') and so on.

Can someone help?

like image 886
itays02 Avatar asked Dec 21 '17 13:12

itays02


1 Answers

As mentioned, GET or HEAD requests cannot have a body. If your data is large, you should move to a POST request.

However, if the parameters you want to use are short like the ones in the example, you should use query strings:

var url = "bla.php";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.send(null);

on the node side, assuming you use express, you can read the variables using:

var somevariable = req.query.somevariable;
var anothervariable = req.query.anothervariable;
like image 70
Gilthans Avatar answered Sep 22 '22 13:09

Gilthans