我對Node.js相當陌生,而且遇到一些問題。發送後無法設置標題。 (nodejs錯誤)
我收到以下錯誤,當我嘗試打開127.0.0.1:3000/bejelentkezes:
POST /bejelentkezes 500 550.784 ms - 2259
GET /css/404.css 304 2.751 ms - -
1
sikeres bejelentkezes
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:371:11)
at ServerResponse.header (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\response.js:730:10)
at ServerResponse.send (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\response.js:170:12)
at done (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\response.js:967:10)
at Object.exports.renderFile (C:\Users\denes\Documents\e_wallet\node_modules\pug\lib\index.js:412:12)
at View.exports.__express [as engine] (C:\Users\denes\Documents\e_wallet\node_modules\pug\lib\index.js:455:11)
at View.render (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\view.js:128:8)
at tryRender (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\denes\Documents\e_wallet\node_modules\express\lib\response.js:971:7)
這是我的代碼:
var express = require('express');
var router = express.Router();
var tools = require('./adatbazis_v2');
router.get('/', function(req, res, next) {
res.render('login');
});
router.post('/', function(req,res,next) {
if (!req.body.email || !req.body.password) {
console.log('valami nincs kitoltve');
} else {
tools.checkUser(req.body.email, req.body.password, function(callback) {
if(callback == 1){
console.log("sikeres bejelentkezes");
res.render('index');
} else {
console.log('sikertelen bejelentkezes');
res.render('login');
}
});
}
});
module.exports = router;
,這是功能:
checkUser: function (felhasznalonev, jelszo, callback) {
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
connection.query('SELECT COUNT(*) AS szamlalo FROM felhasznalok WHERE fhsz_email="' +
felhasznalonev + '" AND fhsz_jelszo= "' + md5(jelszo) +'";', function (error, results, fields) {
console.log(results[0].szamlalo);
callback(results[0].szamlalo);
});
connection.close();
}
編輯1: 我更新我的代碼,但我仍然收到錯誤。
router.post('/', function(req,res,next) {
var l_status = 0;
console.log('l_status: '+l_status);
if (!req.body.email && !req.body.password) {
console.log('valami nincs kitoltve');
} else {
l_status = tools.checkUser(req.body.email, req.body.password, function(callback) {
return callback;
});
if(l_status == 1)
res.render('index');
else
res.render('login');
}
});
錯誤:
GET /bejelentkezes 304 1776.456 ms - -
GET /css/signin.css 304 5.524 ms - -
GET /favicon.ico 200 7.638 ms - 32038
l_status: 0
POST /bejelentkezes 500 728.901 ms - 2259
GET /css/404.css 304 13.212 ms - -
1 (this is checkuser output)
編輯2 - 更信息
App.JS:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var index = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var notfound = require('./routes/error');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('trust proxy', 10);
app.use(session({
secret: 'E355A874F571C',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
// Authentication and Authorization Middleware
var auth = function(req, res, next) {
if (req.session && req.session.user === "denes" && req.session.admin)
return next();
else
return res.sendStatus(401);
};
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/rogzit', index);
app.use('/bejelentkezes', login);
app.use('/404', notfound);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
/*var err = new Error('Not Found');
err.status = 404;
next(err); */
req.redirect('/404');
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
的package.json:個
{
"name": "e_wallett",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.17.1",
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"express": "~4.15.2",
"morgan": "~1.8.1",
"pug": "~2.0.0-beta11",
"serve-favicon": "~2.4.2"
}
}
Adatbazis_v2.JS:
var mysql = require('mysql');
var md5 = require('md5');
var connection = mysql.createConnection({
host : 'localhost',
user : 'usr',
password : 'pw',
database : 'dbname'
});
module.exports = {
checkUser: function (felhasznalonev, jelszo, callback) {
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
connection.query('SELECT COUNT(*) AS szamlalo FROM felhasznalok WHERE fhsz_email="' +
felhasznalonev + '" AND fhsz_jelszo= "' + md5(jelszo) +'";', function (error, results, fields) {
console.log(results[0].szamlalo);
callback(results[0].szamlalo);
});
connection.close();
},
getTranzakciok: function() {
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
});
connection.query('SELECT * FROM tranzakciok";', function (error, results, fields) {
console.log(results[0]);
});
}
}
哈巴狗的index.js的421次行:
// support callback API
if ('function' == typeof options) { //412th LINE
fn = options, options = undefined;
}
if (typeof fn === 'function') {
var res;
try {
res = exports.renderFile(path, options);
} catch (ex) {
return fn(ex);
}
return fn(null, res);
}
options = options || {};
options.filename = path;
return handleTemplateCache(options)(options);
};
我,我的英語錯誤表示歉意,並感謝ü幫助。
很難從您發佈的代碼說,[這個問題](https://stackoverflow.com/questions/7042340/error-cant-set-headers-之後他們被髮送到客戶端)可能是相關的。具體來說,如果傳遞給'checkUser'的回調以某種方式被調用兩次,那可能是原因。 – bmceldowney
無論什麼時候調用兩次,我都有這個問題。我通常通過重構來解決這個問題,以確保代碼以正確的順序執行,並且在我的響應之前添加'return',因爲您應該只發送一個響應。 – reedb89
@ reedb89謝謝你的回覆。我更新了我的代碼,但它仍然不起作用。 – G3ph4z