Axios POST request sends data to Express server but Error 404

Tags: , , , ,



Axios POST request sends data to Express sever but Error 404

Hello, world, I am trying to build a user authentication server for a project I am working on, but I am running into a problem trying to send a POST request to my Node.js Express server.

I want to send a POST request using Axios containing a username and password from the browser. But once sending the request it gives me a 404 Not Found error. The request has to go to http://website/api/login and my Node.js code should return either “authed” or “invalid”. I tested the API inside Postman and that seems to be working. I also exported the request code from Postman and tested it with fetch API, xhr, and Axios, all returning the same result.

The server receives the data and handles it properly, but when I look in the Chromium debugger it appears that the request URL is just http://website/ and not http://website/api/login. I am honestly lost and I have tried what feels like everything, but I can’t seem to make it work. Any help in pointing me in the right direction would be amazing! Thank you!

The code I use for the POST request is:

    const username = document.getElementById("username").value;
        const password = document.getElementById("password").value;

        const data = JSON.stringify({"username": username, "password":password});

        const config = {
            method: 'post',
            url: 'http://website/api/login',
            headers: {
                'Content-Type': 'application/json'
            },
            data : data
        };

        axios(config).then(function (response) {
            console.log(JSON.stringify(response.data));
        }).catch(function (err) {
            console.log(err);
        })
    }

This is what I see in the Chromium debugger: Headers

This is my Node.js / Express code:

app.post('/api/login', function (req, res, next) {
    scriptFile.authUser(req.body, function (err, state) {
        if (err) console.log(err);
        else {
            if (state) {
                res.send("authed");
            } else {
                res.send("invalid");
            }
        }
    });
})

Thank you for any help I can get.

Answer

I am stupid,

Breakdown of what happened:

Everything was working fine except that I put the input data and submit button inside a form, which will refresh the page…

I fixed it by changing the form to a div.



Source: stackoverflow