在 Node/express 端,我尝试向我刚刚创建的端点发出 get 请求。
正确的做法是什么?我可以使用 fetch 库(isomorphic-fetch)
我的尝试:
router.get('/displayweather', function(req, res) {
fetch('/weather')
.then(function(response){
res.send(response);
});
});
router.get('/weather', function(req, res){
var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json';
fetch(fetchUrl)
.then(function(response){
if (response.status >= 400) {
throw new Error("Bad request response from server");
}
return response.text();
}).then(function(body) {
res.send(body);
});
});
还有另一个 router.get(..) 方法使用外部 API 检索天气数据
最佳答案
我会忘记第一部分并专注于您添加的代码:
服务器
router.get('/weather', function(req, res){
var fetchUrl = 'http://api.wunderground.com/api/xyz-token/conditions/q/CA/San_Francisco.json';
fetch(fetchUrl)
.then(function(response){
if (response.status >= 400) {
throw new Error("Bad request response from server");
}
// return json
return response.json();
}).then(function(body) {
// but stringify it when you send it
res.send(JSON.stringify(body));
});
});
客户端
fetch('/weather')
.then(function (json) {
return JSON.parse(json);
})
.then(function (data) {
// do something with the data
})
关于javascript - 请求自己的 API 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003865/