Sails.js生产环境不会在badRequest上返回JSON响应,但是dev环境会这样做

正如标题所述,我的sails应用GET请求到一个特定的路由/控制器函数返回badDequest与JSON在开发环境,但不是在产品环境。 为什么是这样?

这里是控制器function:

index: function(req, res) { async.auto({ companies: function(cb) { User.findOneById(req.session.user.id) .populate('companies') .exec(function(err, user) { if(err) { var badRequestData = { error: err }; return cb(badRequestData, null); } else if(user.companies.length == 0) { var badRequestData = { error: "This user has no associated companies." }; return cb(badRequestData, null); } cb(null, user.companies) }); }, validateForNullCompanies: ['companies', function(cb, results) { var nullCompanies = _.where(results.companies, { stripeAccountId: null }); if(nullCompanies.length > 0) { var badRequestData = { error: "This user needs to authenticate stripe with their company." }; return cb(badRequestData, null); } else { return cb(); } }] }, function(err, results) { if (err) { return res.badRequest(err); } return res.ok(); }); }, 

刚碰到这个,

如果你看http://sailsjs.org/documentation/reference/response-res/res-bad-request中的说明,它说

默认情况下,如果应用程序在“生产”环境中运行(即process.env.NODE_ENV ==='production'),则指定的错误(err)将被排除。

看看api/responses/badRequest.js我们可以看到下面的代码:

 // Only include errors in response if application environment // is not set to 'production'. In production, we shouldn't // send back any identifying information about errors. if (sails.config.environment === 'production') { data = undefined; } 

所以,如果你评论这一点,我相信你会在生产中得到你想要的结果。 同时,这似乎是在这里有一个原因,所以也许发回自定义错误代码与res.send([statusCode], body)身体是你的JSON,或者创build一个较less的描述性解释的客户端处理的不好的要求。

类似finderizer提供的答案,如果你检查api / responses / badRequest.js,实际的代码应该是这样的:

  // Only include errors in response if application environment // is not set to 'production'. In production, we shouldn't // send back any identifying information about errors. if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { data = undefined; } 

原因在评论中已经说明了。 如果仍然认为要在生产环境中显示错误消息,而不是注释掉这一行,实际上可以在config / env / production.js中添加项“keepResponseErrors”并将其设置为true。 喜欢这个:

 module.exports = { keepResponseErrors: true }; 

这样,就不需要改变每个api / response js文件。