Reputation: 3
I'm new to nodejs, and express, and While combing through some code I came across this, What exactly does it mean? and How do I send a POST request to this (using cURL)?? There are no data-fields specified.
app.post('/', limiter, (req, res, next) => {
let {
token
} = req.body;
if (token) {
return res.send('congrats this is your first post request')
}
res.send('not good');
});
Having used flask I have a general idea about what's going on... But I don't understand this part
let {
token
} = req.body;
Can someone please explain what is going on here? Whatever I try, It isn't accepting any POST request. and isn't returning what I want it to. Please excuse me if this doubt seems too trivial, But I haven't seen this anywhere on the internet.
Upvotes: 0
Views: 1452
Reputation: 91
That is assigning the value of req.body.token
to a variable named token
. The same as doing this:
let token = req.body.token;
If you want to curl
this endpoint your data should be JSON something like this:
curl -H "Content-Type: application/json" \
-X POST \
-d '{"token":"<your token here>"}' \
<your url>
Upvotes: 2
Reputation: 3
For posterity, I've added an annotated explanation of the entire script below to assist you in following what it's doing.
/* Sets up a route in express-js */
app.post('/', limiter, (req, res, next) => {
/*
Destructured Variable Assignment (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
The "token" variable is copied from "token" key in "req.body" object (req.body.token).
You probably have bodyParser somewhere in your app that's extracting the body as a JSON for you.
*/
let {
token
} = req.body;
/* Checks "token" for truthiness */
if (token) {
/* sends a response (using return to exit this handler function) */
return res.send('congrats this is your first post request')
}
/* Sends a response since the if statement did not call return. */
res.send('not good');
});
This file is equivalent:
app.post('/',limiter,(req,res,next)=>{
if (req.body.token){
return res.send('congrats this is your first post request');
}
res.send('not good');
});
Upvotes: 0
Reputation: 917
FYI: The following might be helpful.
ES2015 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope variables (and constants) in JavaScript.
Before ES2015, JavaScript had only two types of scope: Global Scope and Function Scope.
It is usually best to get in the habit of using let to avoid scoping issues.
You can find more detailed examples here
Upvotes: 0