简体   繁体   中英

Node.js GET request

I'm making an API and in one of my GET methods i need to make a GET request to another API. In order to do that first i need to select the url depending on a parameter in the route. My code is something like this:

const express = require('express');
const request = require('request');

const router = express.Router();

router.get('/get/:keyword?', (req,res) =>{

        let keyword = req.params.keyword;
        
        let url;
        if(keyword == ""){
            url = 'some string';
        }else{
            url = 'another string';
        }

        request(url, {json:true}, (error, response, body) => {
            if(error){
                res.send("Something went wrong");
            }else{
                res.send(body);
            }
        });

});

However, i'm getting an error like if the "if" block is being ignored. I read some sites and I believe it's because the request function is asynchronous, but I don't know how i can solve it.

Any help is appreciated. Thanks in advance!

As you've mentioned the request you are making is asynchronous you need to handle it within an async function because you don't know when it resolves.

router.get('/get/:keyword?', async (req,res) => {
    let keyword = req.params.keyword;
    
    let url;
    if(keyword === "") {
        url = 'some string';
    } else {
        url = 'another string';
    }

    try {
      const res = await request(url, {json:true});
      res.send(res)
    } catch(err) {
      console.log(err)
    }
});

or you can use .then() style to handle the promises if you don't want to use async..await syntax

router.get('/get/:keyword?', (req,res) => {

    let keyword = req.params.keyword;
    
    let url;
    if(keyword === ""){
        url = 'some string';
    }else{
        url = 'another string';
    }

    request(url, {json:true}).then(res => {
       // do something with the result
       res.send(res.json())
     }).then(err => console.log(err))
});

May it be because you forgot to close the function with the ')' at the end of the router.get? like

router.get('/get/:keyword?', (req,res) => {

        let keyword = req.params.keyword;
        
        let url;
        if(keyword == ""){
            url = 'some string';
        }else{
            url = 'another string';
        }

        request(url, {json:true}, (error, response, body) => {
            if(error){
                res.send("Something went wrong");
            }else{
                res.send(body);
            }
        });

}); // <--- here you missed the ')'

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