Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access data send by xhr request in node.js

Im sending some text from a textbox to node.js express server by XMLHttpRequest:

var text = document.getElementById("textBox").value;
    console.log(text);
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
    else
    {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 || xmlhttp.status==200)
        {
        document.getElementById("textBox").value =xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","http://127.0.0.1:3000/",true);
    xmlhttp.send(text);

My question is how to access it in my server :

var http = require("http");
var url = require("url");
var qs = require('querystring');
var path = require('path');
var bodyParser = require('body-parser');
var express = require('express');

var app = express();
// start endle req\res
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(req,res){
    console.log("request method :" + req.method);
    res.end("OK");
});

// listen at local host:3000
var server = app.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

The string appears as request payload and i dont want to use jQuery.

like image 343
Itsik Mauyhas Avatar asked Nov 08 '14 16:11

Itsik Mauyhas


People also ask

How do you send data as response in node JS?

Methods to send response from server to client are: Using send() function. Using json() function.

Can I use XMLHttpRequest in node?

node-XMLHttpRequest is a wrapper for the built-in http client to emulate the browser XMLHttpRequest object. This can be used with JS designed for browsers to improve reuse of code and allow the use of existing libraries.


1 Answers

Because of how bodyParser accepts the body of a request, you have to set the request header "Content-Type" to 'application/json' for your request to work properly. This is very simple to accomplish; a simple xmlhttp.setRequestHeader('Content-Type', 'application/json') will do the trick.

like image 189
Leon Chou Avatar answered Sep 30 '22 18:09

Leon Chou