2 回答
TA贡献1895条经验 获得超3个赞
正如您所提到的,您发出的请求是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))
});
TA贡献1946条经验 获得超4个赞
可能是因为你忘记关闭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 ')'
添加回答
举报