Answer the question
In order to leave comments, you need to log in
Why is ajax not being processed?
Actually, ajax is sent like this:
var form = document.querySelector('#reg');
form.addEventListener('submit', event => {
event.preventDefault();
var json = JSON.stringify({
name: "Виктор",
surname: "Цой"
});
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reg', true);
xhr.send(json);
});
app.use(bodyParser.urlencoded({extended: true}));
app.post('/reg', (req, res) => {
console.log(req.body);
});
Answer the question
In order to leave comments, you need to log in
everything that was discussed earlier was wrong))
I decided to repeat the mistake myself and indeed, when sending via XMLHttpRequest, the
node does not complain about parsing the request.
and now the magic...
after xhr.open('POST', '/reg', true);
add:
spell 1:
spell 2:
all other code remains as in the question.
PS
option 2, we use jQuery ajax, it correctly puts down the headers.
Below is the code that I tested, everything works for me
<html>
<head>
<title>TEST</title>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
</head>
<body>
<form id="reg">
<input type="submit"/>
</form>
<div id="select_div"><a href="#" id="select_link">Send test data</a></div>
<script type="text/javascript">
$(function(){
$('#select_link').click(function(e){
e.preventDefault();
console.log('Send test data');
var data = {
name: "Виктор",
surname: "Цой"
};
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/reg',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
});
});
var form = document.querySelector('#reg');
form.addEventListener('submit', event => {
console.log('Form submited');
event.preventDefault();
var json = JSON.stringify({
name: "Виктор",
surname: "Цой"
});
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reg');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(json);
});
</script>
</body>
</html>
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.post('/reg', function(req, res){
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.get('/', function(req, res) {
res.sendfile('views/test.html', {root: __dirname })
});
app.listen(10240);
{
"name": "testapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0",
"body-parser": "1.8"
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question