简体   繁体   中英

How to use the GET and POST method in the same endpoint using nodejs / express

Problem

Hello,

I would like to know how I can create an Endpoint that first uses the POST method to login and obtain the token and then use that Token and use it in a GET method to access some data.

As you will see in the code, I currently have the logic of the POST apart and the GET apart, but my intention is to be able to have an endpoint that uses both methods.

The idea would be that after the POST method returns the token to me, I can use it later in the GET method.

I will appreciate your help and your prompt response!

code

app.post('/api/datas/login', async(req, res) =>{
  const url = '...';
  const options = {
    email: process.env.EMAIL,
    password: process.env.PASSWORD
  }
  const call = await axios.post(url, options)
  const token = call.status === 200 ? call.data.token : null;
  res.send({
    status: call.status,
    message: 'Logged In'
  })
});

app.get('/api/datas/alldata', async(req, res) =>{
  try {
    const url = '...'
    const call = await axios.get(url,{ 
      headers: {
        "Authorization" : `Bearer ${token}` //I need to use the token value from the POST method here!
      }
    });
    const data = call.status === 200 ? call.data : null;
    console.log(data);
    res.status(200).json(data);

  } catch (error) {
    res.status(500).send({ message: error });
  }
})

Yes, it should be possible (though not recommended) if you use app.all() instead of post() or get() .

You can get the method of the request and act accordingly by looking at req.method .

For more info: https://expressjs.com/en/guide/routing.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM