简体   繁体   中英

Can't fulfill a get request using express.js?

Here is my server code:

express
  .Router()
 .post('/authFB', async (req, res) => {
   // const agent = express();
    req.query = {
      client_id: 'ID',
      redirect_uri: `https://localhost:3000/`,
      client_secret: 'SECRET',
      code: Object.keys(req.body)[0]
    };

    req.baseUrl = `https://graph.facebook.com`

    const v = await req.get(`/v3.2/oauth/access_token`)
     v.body
  })

Problem I'm having is 'v' is always undefined - I've tested the facebook request via PostMan and it's working - it seems though my get request is never fulfilled.

I think that should be more like this

const got = require('got'); // I am using got for api call
express
    .Router()
    .post('/authFB', async (req, res) => {
        // const agent = express();
        const query = {
          client_id: 'ID',
          redirect_uri: `https://localhost:3000/`,
          client_secret: 'SECRET',
          code: Object.keys(req.body)[0]
        };
        const baseUrl = `https://graph.facebook.com`

        const v = await got(`${baseUrl}/v3.2/oauth/access_token`, { query });
        console.log(v.body);
        res.send(v.body);
    });

Here the data is fetched by 'got' and the response can be sent back to the client or use it in whatever way possible.

What you are doing here would be an antipattern because you are trying to edit the express request object which is not recommended unless used for authentication and other actions which are required for application level.

Also, that req is express.Request type. It doesn't have a get() property on it. Check this for your reference.

Hope this explains your question well enough!!! cheers :)

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