很抱歉,我尝试使用log4js在express中设置api调用上的日志,而在尝试记录拼写时,我对此卡住了。
http_outgoing.js:503
throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
at ServerResponse.setHeader (_http_outgoing.js:510:3)
at ServerResponse.header (/src/react/impex/jumbo-react-flat/apilogica/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/src/react/impex/jumbo-react-flat/apilogica/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/src/react/impex/jumbo-react-flat/apilogica/node_modules/express/lib/response.js:267:15)
at Request.request.get [as _callback] (/src/react/impex/jumbo-react-flat/apilogica/controllers/database.js:62:40)
at self.callback (/src/react/impex/jumbo-react-flat/apilogica/node_modules/request/request.js:185:22)
at Request.emit (events.js:180:13)
at Request.emit (domain.js:422:20)
at Request.onRequestError (/src/react/impex/jumbo-react-flat/apilogica/node_modules/request/request.js:881:8)
这是我使用log4js的log函数,它接收请求对象,并为log操作获取一些不同的参数
var logger = require('log4js');
exports.logapi = function (service,vars) {
var ip = vars.connection.remoteAddress;
debugger;
logger.configure({
appenders: {
out:{type:'console'},
access: { type:'dateFile', filename: '../logs/access.log', category:'info' } ,
error: { type:'dateFile', filename: '../logs/error.log', category:'error' },
}
});
log = logger.getLogger('access');
console.log(vars.query.canal);
log.info('Servicio:'+service+ '; Fecha:' + Date.now() +'; Canal:'+vars.query.canal+'; IP'+ip+'; Usuario:'+vars.query.user+' token:'+vars.query.token);
return;
}
这是当api函数获得请愿时我如何调用log函数,这是另一个模块函数
var apicall = require('./log');
exports.getproduct = function (req, res) {
res.header('Content-Type', 'application/json');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
var reqlog=req;
apicall.logapi('setnewproduct',reqlog);
request.get({
"headers": { "content-type": "application/json" },
"url": "http://localhost:3001/controller_producto/productos/"+req.params.id
}, (error, response, body) => {
if(error) {
return res.sendStatus(400).json({
error: 'Que verguenza! Ocurrio un error, intentalo nuevamente en unos minutos'
})
}else{
return res.send(body);}
});
};
答案 0 :(得分:1)
是的,问题是在Express中,您无法在向客户端发送响应后设置标头,在这种情况下,您需要使用默认的错误处理程序。参见: