2016-02-27 43 views
0

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

} , 
+0

你能至少標誌着它沒有在工作線或給予錯誤或什麼? – Datsik

+0

@Datsik完成。真奇怪的部分是我有其他代碼...在同一個模塊中... ...按預期工作。 put的調用是一個郵遞員是一個相似的代碼複製到相同的模塊工作。 –

+0

您是否嘗試過['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

回答

1

取決於你如何撥打電話,將取決於其中的參數顯示請求對象(REQ)上。

由於要發送與應用程序/ JSON頭JSON對象,該對象被添加到req.body。具有URL路徑的請求將被添加到req.params。根據documentation req.params是一個包含從URL路徑解析的參數值的對象。例如,如果您有route/user /:name,則URL路徑中的「name」將作爲req.params.name提供。該對象默認爲{}。'

所以如果你想通過req.params訪問參數,你可以改變你的請求到'/updateProfile?gravatarURL=www.someurl.com,否則如果你傳遞一個JSON對象,它將在req.body中可用。所以你的解決方法是多餘的,因爲按設計你想訪問的內容已經在req.body中安全了。

該文檔不做解釋這個的最好的工作,但有一點試驗和錯誤很容易找出你傳遞的值都呈現請求對象了。