问题
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
- Url parameters
e,g, /user/:name
req.param("name") //url parameters
- 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.
- Query string
e,g, /user?nickname=ryan
req.param("nickname") //ryan
来源:https://stackoverflow.com/questions/29715451/give-parameter-with-json-format-in-sails