Я пытаюсь научиться отправлять данные, используя ajax.Когда нажата кнопка отправки, я хочу, чтобы Ajax отправлял данные по определенному маршруту, не связанному с данными и маршрутом, связанным с формой.Тем не менее, Ajax, похоже, ничего не посылает.Я добавил три console.log()
заявления в свой скрипт, но ни один из них не отображается.
HTML и AJAX-код
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form class="" action="/submitData" method="post">
<input type="text" name="name">
<button id="submitForm" type="submit">Submit</button>
<script>
const el = document.getElementById(submitForm);
if (el) {
el.addEventListener('submit', addRecipe);
console.log('Step 1');
}
function addRecipe() {
var recipe = {
param1: 'value1',
param2: 'value2'
};
console.log('step 2')
let xml = new XMLHttpRequest();
xml.open("POST", "/add-recipe", true);
//Specify the type of data to be sent
xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
xml.send(JSON.stringify(recipe));
console.log('step 3');
}
</script>
</body>
</html>
файл server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let urlencodedParser = bodyParser.urlencoded({extended: false});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.listen(7000);
app.post('/add-recipe', function(req, res) {
var recipe = req.body.recipe;
console.log(recipe);
});
app.post('/submitData',urlencodedParser,function(req, res){
});