J
J
Jake Taylor2022-01-25 18:25:43
JavaScript
Jake Taylor, 2022-01-25 18:25:43

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>


According to the script, the POST request is sent to the root address 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
    });
}


But in the console I get an error:
Uncaught TypeError: URL constructor: / is not a valid URL.


If instead 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

2 answer(s)
J
Jake Taylor, 2022-01-26
@n199a

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);

W
WapSter, 2022-01-25
@wapster92

let url = new URL(window.location.href); which will be 127.0.0.1:3000

wrong
let url = new URL('http://' + window.location.host)

And even this is not equal to the string with the address. In general, why do you use new Url when you are expected to just have a string with a url in your case it's just 'http://' + window.location.host

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question