nicknamecsharp
@nicknamecsharp

Почему не выполняется редирект?

Почему не выполняется редирект в методе обработки роута '/auth/login'? (не ругайте сильно за качество кода))

Сервер возвращает главную страницу по роуту '/', на которой есть форма, к этой странице привязан файл index.js, проверяющий поля на пустоту.

файл app.js
const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();
const PORT = 3000;
const TOKEN_KEY = require('./config').TOKEN_KEY;

app.use(express.json());
app.use(cookieParser());
app.use(express.static(__dirname + '/static'));
app.use(express.urlencoded({ extended: true }));

try {
    app.listen(PORT, () => {
        mongoose.connect('mongodb://127.0.0.1:27017/libraryprj');
        console.log('server is running');
        console.log('db is ok');
    });
} catch (e) {
    console.log('error');
}


const userSchema = new mongoose.Schema({
    login: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    surname: {
        type: String,
        required: true
    },
    role: {
        type: String,
        required: true
        // TEACHER || STUDENT
    },
    pwdhash: {
        type: String,
        required: true
    }
});

const User = mongoose.model('user', userSchema);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.get('/main', async (req, res) => {
    const token = req.cookies.access_token;
    if (!token) {
        return res.status(400).send(`<h1>Доступ запрещен (попытка войти без авторизации)</h1>
        <a href="/">Вернуться на главную страницу для авторизации</a>`)
    }
    try {
        const data = jwt.verify(token, tokenkey);
        const userId = data.userId;
        const user = await User.findOne({_id: userId});
        if (user.role == 'TEACHER') {
            res.sendFile(__dirname + '/teachermain.html');
        } else {
            res.sendFile(__dirname + '/studentmain.html');
        }
    } catch (error) {
        return res.status(400).json({
            msg: "Something wrong with token",
            error: error
        });
    }
});



app.post('/auth/reg', async (req, res) => {
    // добавлять юзера в бд
});

app.post('/auth/login', async (req, res) => {
//app.post('/', async (req, res) => {
    console.log(req.body);
    const {login} = req.body;
    const {pwd} = req.body;
    if (login == null || pwd == null) {
        return res.status(400).json({
            msg: "No login or pwd"
        });
    } else {
        const user = await User.findOne({login: login});
        if (!user) {
            return res.status(400).json({
                msg: "user was not found (incorrect data)"
            });
        }
        const isPwdCorrect = bcrypt.compare(pwd, user.pwdhash);
        if (!isPwdCorrect) {
            return res.status(400).json({
                msg: "wrong pwd"
            });
        }

        const token = jwt.sign({
            userId: user._id
        }, TOKEN_KEY,
        {
            expiresIn: '10sec'
        });

        return res
        .cookie("access_token", token)
        .status(200)
        .redirect('/main');
    }
});


Файл index.js
const login = document.querySelector('#login');
const pwd = document.querySelector('#password');

const enterBtn = document.querySelector('#enter');
const enterForm = document.querySelector('#enterform');

enterBtn.addEventListener('click', async (evt) => {
    evt.preventDefault();
    if (login.value == '' || pwd.value == '') {
        if (login.value == '') {
            login.classList.add('is-invalid');
        }
        if (pwd.value == '') {
            pwd.classList.add('is-invalid');
        }
    } else {
        await axios.post('/auth/login/', {
            login: login.value,
            pwd: pwd.value
        });
    }
})
  • Вопрос задан
  • 55 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы