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.
Methods to send response from server to client are: Using send() function. Using json() function.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With