Get access data for xhr request in node.js

Im sending text from a text field to node.js express server via 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 on 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 is displayed as the request payload, and I do not want to use jQuery.

+5
source share
2 answers

Due to the way bodyParser accepts the request body, you have to set the "Content-Type" request header to "application / json" for your request to work correctly. It is very simple to do; just xmlhttp.setRequestHeader('Content-Type', 'application/json') will do the trick.

0
source

You can read the request body via req.body :

 app.post('/', function(req,res){ console.log("request method :" + req.method); console.log("request body :" + req.body); res.end("OK"); }); 
-2
source

Source: https://habr.com/ru/post/1206488/


All Articles