使用Node和Express,如何从server.get(..)内部调用远程API
由于CORS问题,我想从我的node express服务器内部调用外部REST API。也就是说,我有这样的代码显然不起作用,因为它不会返回。
我怎样才能完成这项工作并返回外部呼叫的结果?
const server = express();
server.put('/callme',(req,res) => {
axios
('', 'put', { zip: 10530 })
.then((resp: any) => {
console.log(' success' + resp.data);
})
.catch(function(error: any) {
console.log(error.message);
});
}
回答如下:
Axios返回Promise
,在.then()
中解析。为了将响应数据返回给客户端,您需要使用res.send()
返回它。
const server = express();
server.get('/callme', (req, res) => {
axios
.get('http://weather/restapi?zip=10530')
.then((resp: any) => {
res.send(resp.data);
})
.catch(function(error: any) {
console.log(error.message);
});
}
最好将天气API响应缓存一段时间,并为后续请求提供缓存响应。