我只是圍繞一個奇怪的錯誤工作。我使用有效的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