Search code examples
javascriptnode.jsxmlhttprequest

Change browser url after post request in node server


I am implementing a sign up page in which I want to change the browser url after submitting the form and sending post request. Indeed I want the server to serve another static file after receiving post request. How can I do that?

Here is my xhr request in client side using vanilla js:

function signup(e) {
        var data = {
            name: _elements.fullname.value,
            username: _elements.username.value,
            password: _elements.password.value
        };

        data = JSON.stringify(data);

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4 && xhr.status === 200) alert('Signed in successfully!');
        }
        xhr.open('POST', 'signup', true);
        xhr.setRequestHeader('Content-Type', 'text/plain')
        xhr.send(data);
    }

And This is my server.js file:

const http = require('http');
const requestHandler = require('./req-handler').requestHandler;

http.createServer(requestHandler).listen(8080);

req-handler.js:

if (req.method === 'GET') {
        switch (req.url) {
            case '/':
                routeHandler = rootHandler;
                break;
        }
    } else if (req.method === 'POST') {
        switch (req.url) {
            case '/signup':
                routeHandler = signupHandler;
                break;
        }
    }

    if (!routeHandler) {
        routeHandler = staticFileHandler;
    }

    routeHandler(req, res);


    function rootHandler(req, res) {
        req.url = 'signup.html';
        staticFileHandler(req, res);
    }

    function signupHandler(req, res) {
        req.url = 'index.html';
        var jsonData = '';

        req.on('data', data => {
            jsonData += data.toString('utf-8')
        });

        req.on('end', () => {

            staticFileHandler(req, res);
        });
    }


    function staticFileHandler(req, res) {
        console.log(req.url)
        fs.readFile('client/' + req.url, function (err, data) {
            if (err) {
                res.writeHead(500);
                res.write(err.name);
                res.end();
            }
            console.log(data)
            res.writeHead(200);
            res.write(data);
            res.end();
        });
    }

All the static files (.html and .css) are in /client folder. By the way, I do not want to use any library/framework.


Solution

  • You can navigate to a new page, using vanilla js.

    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 200) {
            alert('Signed in successfully!');
            document.location.href = {Your_new_URL}
        }
    }
    

    If a file path can vary - You can always specify it in the response JSON on the server and use it in XHR success-callback.