Я пытаюсь обработать запрос post ajax на сервере узла. Моя проблема в том, что я получаю тело запроса 'undefined'. пожалуйста, помогите мне понять, если я делаю неправильно. Ниже приведен код, который я использую.
функция sendRequest () {
let http = new XMLHttpRequest();
let url = 'http://<hostname>:3000/checkRequest';
let data = {};
data.name = "nameString";
data.age = "ageString";
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.send(JSON.stringify(data));
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState === 4 && http.status === 200) {
alert(http.responseText);
}
};
}
Код обработчика запроса:
// create express app
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
// middleware route that all requests pass through
app.use((request, response, next) => {
console.log('Server info: Request received');
let origin = request.headers.origin;
// only allow requests from trusted origins
if (originWhitelist.indexOf(origin) > -1) {
response.header('Access-Control-Allow-Origin', origin);
}
// only allow get and post requests, separate methods by comma e.g. 'GET, POST'
response.header('Access-Control-Allow-Methods', 'GET, POST');
response.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
response.header('Access-Control-Allow-Credentials', true);
// push through to the proper route
next();
});
app.post('/checkRequest', (request, response) => {
console.log(request.body.name) //undefined
}