Give parameter with json format in sails

空扰寡人 提交于 2019-12-10 21:26:18

问题


In my controllers and other areas where there's a req object, I can access request parameters using req.params('username'). This is fine for normally POSTed data, but I want my API to accept a JSON object in the request body and convert it to parameters that I can still access with req.params().

So for example, if I send this as the POST request body to my controller action:

{'username': 'Chris', 'password': 'mypass'}

I want to be able to get the username and password using req.params('username') and req.param('password').

At the moment the only thing that works is sending the data like this:

username=Chris&password=mypass

Any ideas?


回答1:


When sending a json object, you can access the POST request data in req.body




回答2:


You have to set request header : Content-Type to application/json

One thing I want to clarify,

The req.params is used to get the url parameters

e,g, /user/:name

req.params("name")

And the req.param is more powerful, you can get three data through this method with following priority

  1. Url parameters

e,g, /user/:name

req.param("name") //url parameters 
  1. Body query string or body data

POST HEADER (Optional, default)

Content-Type:application/json

POST BODY - json data

{'username': 'Chris', 'password': 'mypass'}

OR

POST HEADER

Content-Type:application/x-www-form-urlencoded

POST BODY - query string

username=Chris&password=mypass

You can use req.param('password') to get the value you sent.

  1. Query string

e,g, /user?nickname=ryan

req.param("nickname") //ryan


来源:https://stackoverflow.com/questions/29715451/give-parameter-with-json-format-in-sails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!