0

Хочу сделать простую проверку на пользователя с дополнительными возможностями, а именно добавления постов на страницу. В базе лежит пароль от модератора и на сервере осуществляю его проверку, и если он правильный то нужно показать дополнительные поля. После запуска сервера выдает следующую ошибку:

_http_outgoing.js:470
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at Array.write (/media/selin/Data/Documents/WORK/My Projects/Web Developing/GitHub/IgorZaviryukhaA2Lab/lesson_5/5-2_News/node_modules/finalhandler/index.js:285:9)
    at listener (/media/selin/Data/Documents/WORK/My Projects/Web Developing/GitHub/IgorZaviryukhaA2Lab/lesson_5/5-2_News/node_modules/on-finished/index.js:169:15)
    at onFinish (/media/selin/Data/Documents/WORK/My Projects/Web Developing/GitHub/IgorZaviryukhaA2Lab/lesson_5/5-2_News/node_modules/on-finished/index.js:100:5)
    at callback (/media/selin/Data/Documents/WORK/My Projects/Web Developing/GitHub/IgorZaviryukhaA2Lab/lesson_5/5-2_News/node_modules/ee-first/index.js:55:10)
    at IncomingMessage.onevent (/media/selin/Data/Documents/WORK/My Projects/Web Developing/GitHub/IgorZaviryukhaA2Lab/lesson_5/5-2_News/node_modules/ee-first/index.js:93:5)
    at IncomingMessage.emit (events.js:182:13)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

Соответственно код:

const  
    express    = require('express'),  //include express module
    Url        = require('url'),    //include url module
    bodyParser = require('body-parser'),  //for post requests
    mysql      = require('mysql'),  //include mySQL module
    app        = express(),   //server

    connection = mysql.createConnection({  //connecting to database
        host: '127.0.0.1',  //ip adress 
        user: 'admin',  //name of user in mySQL
        password: '123',  //user password
        database: 'news'  //database name
    });

connection.connect(function(err) {  //establishing connecting to DB
    if (err) throw err;   //if we have some exception
    console.log('Connected!');  //if everything is OK
});

app.set('view engine', 'ejs');  //connect ejs to application
app.use('/public', express.static('public'));  //using static folder for css and more
app.use(bodyParser.urlencoded({ extended: true })); //using body parser for POST requests

//generate root page for user
app.get('/', function(request,response) {
    connection.query('SELECT title, text, date FROM news', function(err, result) {
        if (err) throw err;
        response.render('index', { posts: result });
        response.end();
    });
});

app.post('/', function(request, response) {
    connection.query('SELECT password FROM moderator', function(err, result) {
        if (err) throw err;
        if (!req.body) return sendStatus(400);
        var password = result[0].password;

        if (password === request.body.password) {
            response.render('index', { moderator: true });
            response.end();
        } else {
            response.render('index', { moderator: false });
            response.end();
        }
    });
});

app.listen(8080);  //listening to the port

Хочу просто при совпадении передать в index.ejs переменную. Но именно эти куски кода и вызывают ошибку

response.render('index', { moderator: true });

response.render('index', { moderator: false });

Кто знает в чем проблема? Спасибо.

2 ответа 2

1

Не нужно ставить response.end(); после response.render('index', { moderator: true });, т.к. response.render() или response.send() сами вызывают его.

Т.е. просто

if (password === request.body.password) {
        response.render('index', { moderator: true });
    } else {
        response.render('index', { moderator: false });
    }

или вообще

 response.render('index', { moderator: password === request.body.password});

P.S. У вас пароль хранится в незащищенном виде, если вы планируете использовать ваше приложение "в бою", то рекомендую сохранить хеш пароля и сравнивать введенный пароль с хешем. Для этого можно использовать bcrypt, примеры кода по ссылке.

4
  • Спасибо, частично помогло, но работает только когда на странице index.ejs нету следующего кода: <% if (moderator) { %> <input type="password" placeholder="Password" name="password" class="password"> <button type="submit" class="log-in">Log In</button> <%} else {%> <button type="submit" class="log-out">Log Out</button> <% } %>
    – undefined
    31 окт 2018 в 12:34
  • а можно как-то передать переменную без рендеринга, а то по сути второй раз одну и ту же страницу рендерю?
    – undefined
    31 окт 2018 в 12:36
  • @unsxxn в данном случае нет, в любом случае необходимо рендерить эту же страницу, только с другой переменной
    – RTK
    31 окт 2018 в 12:41
  • понял, а почему на странице index.ejs не работает условие <% if (moderator) { %> /* html */ <% } %>. Когда этот код присутствует выдает ту же ошибку. Может как-то не так я переменную принял?
    – undefined
    31 окт 2018 в 12:45
1

response.render() рендерят страницу и отправляют ее, при этом закрывая соединение. А после этого вы еще раз закрываете соединение через response.end(). Отсюда и ошибка.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.