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:
- Client opens the login page in which he's required to enter the username and the password.
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.
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.