簡體   English   中英

在html中顯示來自nodejs的數據

[英]Display data coming from nodejs in html

如果這是一個重復的問題,我很抱歉。 但是,我正在努力想辦法在 html 中顯示來自我的 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>

首先,您必須設置 api 路由和文件服務路由。 然后您可以調用 api 方法(例如通過 jQuery ajax)並獲取響應數據。

試試這個而不是你的 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!');
});

我現在沒有 nodejs 來測試這個,但這應該給你一個想法。 您必須定義路由。 我為你定義了 .get("/") 所以每個對主 URL 的請求都會調用這個函數。 我還將 Access-Control-Origin 設置為 *. 如果您想稍微保護一下,請從 nodejs 提供靜態文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM