请求拥有API终结点
Request to own API endpoint
在node/express端,我正试图向刚刚创建的端点发出get请求。
正确的方法是什么?我可以使用提取库(同构提取)吗
我的尝试:
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
})
相关文章:
- 如何更改bigquery API中的计费层选项
- Amazon S3 REST API大小不正确
- 客户端服务器REST API captcha实现
- 使用Facebook live API创建实时视频对象时的隐私设置
- 谷歌放置API:按国家或餐馆名称搜索餐馆
- MeteorJS:在带有回调的vzaar api上正确使用wrapAsync
- 是否可以控制获取哪些Google地图脚本(JavaScript API)
- API密钥使用和检查示例
- 谷歌地图API v3不适用于移动浏览器或PhoneGap
- 任何方式使AJAX调用Gmail API,而无需通过JS库
- 谷歌地图JS API+JSON-多个标记没有显示
- 单击超链接时,如何使用Google Maps API v3缩放地图
- 如何在 API 调用后和 if 语句中启用提交按钮
- 与运行长作业(javascript,node.js)的第三方API同步的最佳实践
- 搜索api在mac上显示对话框
- Backbone.js restful json API design
- 标记的实时更新,无需加载页面谷歌地图API V3
- 是否可以使用iframe API在iOS浏览器上播放youtube视频
- 对API数据使用声明性绑定
- Nodejs API控制器,用于在API之间切换