如果这是一个重复的问题,我很抱歉。但是,我正在努力找出一种方法来显示我的nodejs中的数据。
以下是我的data.js代码:
var express = require('express');
var app = express();
var path = require('path');
var data = new Array;
data.push([1,2,3]);
data.push([4,"Test data",6]);
app.use(function (req, res) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.send(data)
//next();
});
app.listen(9000, function () {
console.log('Example app listening on port localhost:9000!');
});
我想在html页面中显示这些数据。任何人都可以在这里帮助HTML / JQuery脚本吗?感谢。
HTML代码:
<script type="text/javascript">
jQuery(document).ready(function($) {
alert('Hello');
$.ajax({
url:"http://localhost:9000",
dataType: 'json',
data: data,
success: success
});
$.get('/', {}, function(data){
// not sure it is the right code
console.log(data);
// then the code to create a list from the array (no pb with that)
});
//function jsonpCallback(data){
// alert("jsonpCallback");
//}
//do jQuery stuff when DOM is ready
});
</script>
<h1>Header Text</h1>
答案 0 :(得分:1)
首先,您必须设置api路由和文件服务路由。然后你可以调用api方法(例如通过jQuery ajax)并获取响应数据。
答案 1 :(得分:0)
尝试使用此代替您的node.js代码:
var express = require('express');
var app = express();
var data = new Array;
data.push([1,2,3]);
data.push([4,"Test data",6]);
app.get('/', function (req, res) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.send(data);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
我现在没有和我一起测试这个节点,但是这应该给你一个想法。你必须定义路线。我为你定义了.get(&#34; /&#34;),因此对主url的每个请求都会调用这个函数。我还将Access-Control-Origin设置为*。如果你想保护一点,请从nodejs提供静态文件。