Node.js GET 请求

我正在制作一个 API,在我的 GET 方法之一中,我需要向另一个 API 发出 GET 请求。为了首先做到这一点,我需要根据路由中的参数选择 url。我的代码是这样的:


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);

            }

        });


});

但是,我收到一个错误,就像“if”块被忽略一样。我读了一些网站,我相信这是因为请求函数是异步的,但我不知道如何解决它。


任何帮助表示赞赏。提前致谢!


蓝山帝景
浏览 104回答 2
2回答

蛊毒传说

正如您所提到的,您发出的请求是asynchronous您需要在异步函数中处理它,因为您不知道它何时解析。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)    }});.then()或者,如果您不想使用async..await语法,则可以使用样式来处理承诺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))});

绝地无双

可能是因为你忘记关闭router.get末尾的')'功能?喜欢router.get('/get/:keyword?', (req,res) => {&nbsp; &nbsp; &nbsp; &nbsp; let keyword = req.params.keyword;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; let url;&nbsp; &nbsp; &nbsp; &nbsp; if(keyword == ""){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url = 'some string';&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url = 'another string';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; request(url, {json:true}, (error, response, body) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(error){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.send("Something went wrong");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.send(body);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });}); // <--- here you missed the ')'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript