[英]How to return data from an api consumed by nodejs to the frontend?
我试图使用的 API 来自第三方,它阻止了跨域,所以我不能用 jquery 或 javascript 来使用它......所以我不得不在 nodejs 中创建一个脚本来使用这个 API......
我想知道如何使用 nodejs 从 API 获取到我的前端的数据,使用 javascript?
请记住,此 nodejs 与我的前端位于一个单独的文件中,并在另一台服务器上运行。
var request = require("../../node_modules/request");
var options = { method: 'GET',
url: 'https://....apimanagement.us2.hana.ondemand.com/bot/v1/...',
qs: { Shop: '..'', PeriodoAte: '...' },
headers:
{ 'postman-token': '822e513f-da5e-4a0b-b403-1dd8fa46e86f',
'cache-control': 'no-cache',
authorization: 'Basic .........',
apikey: '....',
'content-type': 'application/json' },
json: true };
request(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
一种路径是:
最终得到这样的东西进行测试
'use strict'; const Hapi = require('hapi'); const rp = require('request-promise'); const server = Hapi.server({ port: 3000, host: 'localhost' }); server.route({ method: 'GET', path: '/', handler: (request, h) => { const options = { method: 'GET', uri: 'https://./..', qs: {Shop: '..', PeriodoAte: '...'}, headers: { 'postman-token': '822e513f-da5e-4a0b-b403-1dd8fa46e86f', 'cache-control': 'no-cache', authorization: 'Basic .........', apikey: '...', 'content-type': 'application/json' }, json: true }; return rp(options).catch(e => { console.log(`api call failed ${e}`); return 'fail'; }) } }); const init = async () => { await server.start(); console.log(`Server running at: ${server.info.uri}`); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init();
现在你可以用 node 启动它并访问 'localhost:3000/'
类似的东西,希望它有点帮助
编辑: //
在客户端上消费只需使用例如 jquery 来获取上面代码提供的路由
以下是评论中要求的一些客户端示例:
如果您从其他位置提供 html,而不是 hapi api,则需要在 HapiJS 路由中启用 cors。
server.route({
method: 'GET',
path: '/',
config: {
cors: {
origin: ['*'],
additionalHeaders: ['cache-control', 'x-requested-with']
}
},
那么使用这个端点的一种方法是 jquery
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<input type="button" id="Button" value="Fetch"/>
<div id='main'></div>
<script type="text/javascript">
$(document).ready(function () {
$('#Button').click(() => {
$.ajax({
url: "http://localhost:3000/info", success: (result) => {
$("#main").text(result);
}
});
});
});
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.