0

I'm new to javascript and web programming. I'm trying to build a config web page for a product that I wrote using node.js. for this reason i used express as back end and some html,css and javascript on front end. the scenario is this:

  1. Client opens the login page in which he's required to enter the username and the password.
  2. after pressing the login button, the values of username and password are sent to express using a post request to '/login' address and if the credentials are correct, a token as the response will be sent back to client and will be set in the local storage of the client.

  3. Client automatically sends a GET request to '/config' address where a protected html page that verifies the token on load, appears and shows some fields.

the problem is when the second stage completes, client sends GET request to /config but the response doesn't load in the page but i can see the response page in google chrome > Developer tools > Network section.

I'm using axios for sending request and express as back end web server.

here is my back end code using express:

const config = require('config');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const jwt = require('jsonwebtoken');
const port = 3333;
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'webconfig', 'login.html'))
});

app.get('/config', verifyToken,(req, res)=> {
    console.log('GET /config data');
    res.sendFile(path.join(__dirname, 'webconfig', 'config.html'));
});

app.post('/login', (req, res) => {
    console.log('POST /login');
    const {body} = req;
    if (body.username === config.web.username && body.password === config.web.password) {
        const user = {
            id: 1,
            username: 'admin'
        };
        jwt.sign({user}, jwt_secret, {expiresIn: '3000s'}, (err, token) => {
            console.log('Token sent to client');
            res.send({
                token: token,
            });
        });
    } else {
            console.log('User pass mismatch');
        res.redirect('/')
    }
});

this is my js on client side which triggers on button click:

const username = document.getElementById('username');
const password = document.getElementById('password');

async function login() {
axios.post('/login', {
        "username": username.value,
        "password": password.value
        })
    .then(function(res) {
                window.localStorage.setItem('token', res.data.token);
                let token = window.localStorage.getItem('token');
                if (token !== 'undefined'){
                    axios.get('/config',{headers:{Authorization:'Bearer ' + token }})
                    } else {
                    window.location.href = '/'
                }
            })
    .catch(function(err) {
                console.log(err)
            });
    }
}

the verifyToken function is a middleware which verifies the token and calls the next function.

after all I mentioned I'm new to web development so any help is appreciated.

Nima Soufiloo
  • 224
  • 4
  • 18
  • The get function here works and I am not clear about what do you wanna do with it? Server sends a config back on get, but what do you wanna do with the config? you haven't used the response from get – Vishnudev Krishnadas Nov 25 '18 at 18:01

1 Answers1

1

The problem is that you are using axios.

Axios makes XMLHttpRequests. So, when you use axios.get, the page does not load the html response, it just gets it and stores it in in the response object.

To load another page window.location is suggested, but since you also want to send headers, that makes it difficult.

Refer to this, it might just be what you are looking for.

Adding http headers to window.location.href in Angular app

Legolas
  • 105
  • 8
  • I already solved the problem by passing the token in url but its so messy. I'm looking for a solution to set headers and load the next page as I mentioned. unfortunately I couldn't find a solution for this matter. – Nima Soufiloo Nov 26 '18 at 05:45