如何在我的Node.js代理中返回JSON?
我不得不将请求代理到Dota 2 API。 经过一番研究,我find了一种方法,在使用MEAN堆栈构build的API中完成它。 但是,我不知道如何从请求中返回数据。
这是我的节点服务器代码中的路线:
router.get('/api/allheros', function (req, res) { Https.get('https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=FB900D42DC33F4B4FCC62F6C7779BE5D', function (res) { var str = ''; console.log('Response is ' + res.statusCode); res.on('data', function (chunk) { str += chunk; }); res.on('end', function () { console.log(str); //This console logs all the heros correctly }); }); });
控制台日志工作,但我需要数据返回到前端。
您只需将结果parsing为JSON对象,然后使用res.json()
将其返回。 修改你的代码如下,
router.get('/api/allheros', function (req, res) { Https.get('https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=FB900D42DC33F4B4FCC62F6C7779BE5D', function (response) { var str = ''; console.log('Response is ' + response.statusCode); response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { res.json(JSON.parse(str)); }); }); });
注意:内部函数中的res
必须改为response
这样它才不会屏蔽外部函数的res
参数。
- NodeJS检查其他主机的SSLauthentication的有效性
- 如何通过https使用私有GitLab存储库作为与私有令牌的npm依赖关系
- javascript可以指定全局/默认选项来设置HTTPS连接?
- 在NodeJS服务器端保护Firebase存储的外部链接
- Node.js https在Cloud9中不起作用
- express-js服务器中的HTTPS SSL损坏(net :: ERR_CERT_COMMON_NAME_INVALID)
- 在Openshift上使用https创buildExpress JS 4.0应用程序,包括httpredirect
- 使用node.js实现一个简单的代理服务器
- 如何使用node.js https的http代理?