I use postman to test my api
http://localhost:3000/api/books?disabled=true
I want to set disabled=true (or false) and I expect it is a bool
But somehow
const {disabled} = req.query;
console.log(typeof disabled) //I get disabled type of string
How I set my query param boolean type?
I use postman to test my api
http://localhost:3000/api/books?disabled=true
I want to set disabled=true (or false) and I expect it is a bool
But somehow
const {disabled} = req.query;
console.log(typeof disabled) //I get disabled type of string
How I set my query param boolean type?
Share Improve this question asked Nov 9, 2018 at 6:51 coinhndp coinhndp 2,49111 gold badges38 silver badges71 bronze badges 5- Have you tired to set disabled to 1 or 0 ? – Marcia Ong Commented Nov 9, 2018 at 6:53
- It still shows that type of disabled is string – coinhndp Commented Nov 9, 2018 at 6:54
- codippa./how-to-convert-string-to-boolean-javascript – Marcia Ong Commented Nov 9, 2018 at 6:55
-
Just asking, won't it work with a boolean? like
let condition = disabled==='true'
? – lloydaf Commented Nov 9, 2018 at 6:56 - You will need to parse it in the backend. – Marcia Ong Commented Nov 9, 2018 at 7:01
3 Answers
Reset to default 0Regardless of the format (query params, JSON body) it is the job of the backend to parse and validate the request.
So even if you send a parameter like “active=true”, it is still a string, this is how the HTTP protocol works.
For more info ---> https://munity.getpostman./t/how-to-pass-boolean-values-using-postman/1174
let disabled = ( req.query.disabled !== 'false' )
That should do it. As explained in other answers, HTTP does not natively support any non-string or non-stream types (integers, booleans, etc.). The server is tasked with parsing the meaning from the original request format.
Alternatively, you can also do the following to bee more familiar with the intricacies of parsing JSON-based requests.
let disabled = JSON.parse(req.query.disabled)
Here is the screen print of passing boolean as query param
For any reason, if the param returns false, the issues could be that I came across,
- The key defined in @RequestParam has typo
- The key defined in @RequestParam has space
- The key defined in @RequestParam not matching with the key mentioned in postman query param list
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744968217a4603813.html
评论列表(0条)