我只是围绕一个奇怪的错误工作。我使用有效的json和应用程序/ json头文件发送REST PUT调用。什么会阻止sailsjs识别req.params?
在PUT调用的JSON是
{
"gravatarURL": "http://www.gravatar.com/avatar/?d=mm"
}
为什么有效的JSON任何想法不req.params被认可?
处理该替代方法的代码解析JSON身体进入params为
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
@Datsik完成。真奇怪的部分是我有其他代码...在同一个模块中... ...按预期工作。 put的调用是一个邮递员是一个相似的代码复制到相同的模块工作。 –
您是否尝试过['req.allParams()'](http://sailsjs.org/documentation/reference/request-req/req-all-params)?根据[文档](http://sailsjs.org/documentation/reference/request-req/req-params),'req.params'是“含有从URL路径解析参数值的对象。”所以它应该只包含url参数。如果您在请求正文中发送内容,它们将不会包含在'req.params'中。 – Fissio