Javascript 如何将nodejs使用的api中的数据返回到前端?
我试图使用的API来自第三方,它阻止了跨源代码,因此我不能使用jquery或javascript使用它。。。所以我必须在nodejs中创建一个脚本来使用这个API 我想知道如何使用javascript使用nodejs从API到前端获取的数据 记住,这个nodejs与我的前端位于一个单独的文件中,并从另一台服务器运行Javascript 如何将nodejs使用的api中的数据返回到前端?,javascript,node.js,Javascript,Node.js,我试图使用的API来自第三方,它阻止了跨源代码,因此我不能使用jquery或javascript使用它。。。所以我必须在nodejs中创建一个脚本来使用这个API 我想知道如何使用javascript使用nodejs从API到前端获取的数据 记住,这个nodejs与我的前端位于一个单独的文件中,并从另一台服务器运行 var request = require("../../node_modules/request"); var options = { method: 'GET', url:
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.
});
为了使前端与后端(Node.js)通信,您需要一个web服务器来侦听请求。如果你想要简单的东西,你可以用。您还可以使用JavaScript框架,有很多(这是快速入门的好选择) 如果无法在服务器中安装Node.js,另一个选项是使用AWS Lambda快速创建API,您可以通过HTTP请求从前端使用该API。一个路径是:
- 选择一个节点框架(Express,Hapi,…)让我们为这个示例选择Hapi
- 阅读入门指南
- 了解承诺或经历地狱
- 最后用这样的东西进行测试
'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/”
- 多读,多尝试
- 了解节点生产模式和托管
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>
$(文档).ready(函数(){
$(“#按钮”)。单击(()=>{
$.ajax({
url:“http://localhost:3000/info“,成功:(结果)=>{
$(“#main”).text(结果);
}
});
});
});
这是我正在走的一条新路,你能报告我吗?这样我就可以查看和学习了-您必须使您的脚本能够服务于http请求,并让前端使用AJAX请求完成它。如果你想把它当作玩具,那么只需使用express或hapi并遵循相关教程即可。如果你真的想这样做(如在生产中),那么答案就超出了堆栈溢出的范围。我发现你的答案非常好,但是你能通过给出一个我如何在客户机上消费她的例子来完善她吗?但我还是会给你标点符号。我添加了一个jquery示例