2

I am using NodeJS and Express, and I want to get the Username and Password parameters from a request. I've searched for a while now, and I can't find my answer.

I want to accept a user parameter from a cURL command:

curl --request --POST -u USERNAME:PASSWORD -H "Content-Type:application/json" -d "{\"key":\"value\"}" --url https://api.example.com/my_endpoint

In my application:

app.post('/my_endpoint', async (req, res, next) => {
    const kwargs =. req.body;
    const userName = req['?'];
    const password = req['?'];
});
WebWanderer
  • 7,827
  • 3
  • 25
  • 42

2 Answers2

2

You are sending the credentials as a basic-auth header (since you're using curl's -u option). So in order to get the credentials from your request, you need to access this header and decode it. Here's one way to do this:

app.post('/my_endpoint', async (req, res, next) => {
   if(req.headers.authorization) {
     const base64Credentials = req.headers.authorization.split(' ')[1];
     const credentials = Buffer.from(base64Credentials, 'base64').toString('utf8');
     const [username, password] = credentials.split(':');
     console.log(username, password);
   }
});
eol
  • 15,597
  • 4
  • 25
  • 43
0

How do I consume the JSON POST data in an Express application

I would do it this way

Assuming your call includes json content like this :

Remove -u USERNAME:PASSWORD

Edit -d "{ "username": "user", "password": "test" }"

curl --request --POST -H "Content-Type:application/json" -d "{ "username": "user", "password": "test" }" --url https://api.example.com/my_endpoint

Then you can access those variables with :

const userName = req.body.username;
const password = req.body.password;

Be careful, you need to use bodyParser middleware in express in order to be able to access the body variables.

Mizibi
  • 177
  • 9