2 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
正如您所提到的,您發(fā)出的請求是asynchronous您需要在異步函數(shù)中處理它,因?yàn)槟恢浪螘r(shí)解析。
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))
});

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
可能是因?yàn)槟阃涥P(guān)閉router.get末尾的')'功能?喜歡
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 ')'
添加回答
舉報(bào)