Give parameter with json format in sails

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

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

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

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

At the moment, the only thing that works is to send the data as follows:

 username=Chris&password=mypass 

Any ideas?

+3
source share
2 answers

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

+1
source

You must set the request header: Content-Type in the application / json

One thing I want to clarify

req.params is used to get URL parameters

e, g, / user /: name

 req.params("name") 

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

  • URL Parameters

e, g, / user /: name

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

MAIL TURNOVER (optional, default)

 Content-Type:application/json 

POST BODY - json data

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

OR

POSTAL FACTORY

 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 
+4
source

Source: https://habr.com/ru/post/985570/


All Articles