【发布时间】:2016-02-27 00:55:28
【问题描述】:
我刚刚解决了一个奇怪的错误。我正在发送带有有效 json 和 application/json 标头的 REST PUT 调用。
PUT调用中的json是
{
"gravatarURL": "http://www.gravatar.com/avatar/?d=mm"
}
关于为什么在 req.params 中无法识别有效 json 的任何想法?
处理将json主体解析为参数的代码是
updateProfile: function(req, res) {
tag = 'UserController.updateProfile' ;
user = {} ;
user.id = req.session.userId ;
if (!user.id){
user.id = 0 ;
}
/* the following line of code should result in params with elements */
params = req.params ;
/* what I get is params == [] */
/* this is the start of the workaround */
if ( params.length == 0) {
try {
/* copying the body creates a valid json object */
params = {}
params.body = req.body ;
params = params.body ;
/* gravatarURL is the parameter sent in via the REST PUT call */
user.gravatarURL = params.gravatarURL ;
} catch (e){
/* ignore and pass through to error with no params */
console.log( tag + '.error: ' + e.message ) ;
}
} else {
/* this is what I expect to be able to do */
user.gravatarURL = req.param['gravatarURL'] ;
}
if ( user.id && user.gravatarURL) {
console.log( tag + '.update.start' ) ;
User.update({ id: user.id }, { gravatarURL: user.gravatarURL }, function(error, updatedUser) {
if (error) {
console.log( tag + '.update.error: ' + error.message ) ;
return res.negotiate(error);
} else {
console.log( tag + '.update.finish: ' ) ;
return res.json(updatedUser);
}
});
} else {
if ( !user.id ) {
error = {} ;
error.message = 'authorisation required. please login.' ;
return res.badRequest({error:error}) ;
}
if ( !user.gravatarURL ) {
error = {} ;
error.message = 'gravatarURL: required' ;
return res.badRequest({error:error}) ;
}
}
} ,
【问题讨论】:
-
你能至少标记它不工作的行或给出错误或任何东西吗?
-
@Datsik 完成。真正奇怪的部分是我有其他代码......在同一个模块中......按预期工作。 put 调用是一个邮递员,将类似代码复制到同一模块中。
-
你试过
req.allParams()吗?根据docs,req.params是“一个包含从 URL 路径解析的参数值的对象”。所以它应该只包含 url 参数。如果您在请求正文中发送内容,它们将不会包含在req.params中。
标签: javascript json node.js sails.js