Answer the question
In order to leave comments, you need to log in
Why isn't a POST request sent using XMLHttpRequest?
Testing locally at 127.0.0.1:3000 .
There is a script that receives the value of the input field on the onkeyup event and using XMLHttpRequest the value is sent from the client side to the NodeJS server side:
<script>
function search() {
let method = 'POST';
let url = new URL("/");
let searchValue = document.getElementById('search').value;
console.log('[' + url.href + '] searchValue:' + searchValue);
let searchRequest = new XMLHttpRequest();
searchRequest.open(method, url);
searchRequest.send({searchQuery: searchValue});
}
</script>
let url = new URL("/");
, which is processed on the server like this:const express = require('express');
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false});
const jsonParser = bodyParser.json();
app.use(jsonParser);
app.use(urlencodedParser);
// some code ....
exports.index = function (request, response) {
let giftCertificates;
let searchValueFromPage = JSON.stringify(request.body.searchQuery);
// if the user entered search request, then the event "onkeyup" will run
if(searchValueFromPage) {
giftCertificates = search(searchValueFromPage, content);
} else {
giftCertificates = content;
}
response.render('index.hbs', {
title: 'Gifts main page',
text: 'This is the left box',
gifts: giftCertificates
});
}
Uncaught TypeError: URL constructor: / is not a valid URL.
let url = new URL("/");
I write let url = new URL(window.location.href);
, which will be equal to http://127.0.0.1:3000/
, then after I enter the value in input
, the request does not reach the server along the way http://127.0.0.1:3000/
, why?
Answer the question
In order to leave comments, you need to log in
I figured it out, on my server I was configured to process only a GET request, I added for POST:
indexRouter.get('/', indexController.index);
indexRouter.post('/', indexController.index);
let url = new URL(window.location.href); which will be 127.0.0.1:3000
let url = new URL('http://' + window.location.host)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question