2016-03-19 6 views
0

これは繰り返し質問ですが残念です。しかし、私は自分のnodejsからのデータをhtmlで表示する方法を見つけようとしています。私はhtmlページでこのデータを表示したいhtmlのnodejsから表示されるデータを表示

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!'); 
}); 

以下は、私のdata.jsコードです。誰でも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> 

答えて

1

まずあなたは、APIのルートおよびルートにサービスを提供するファイルを設定する必要があります。次に、apiメソッドを呼び出して(例えば、jQuery ajax経由で)応答データを取得することができます。

+0

コードサンプルを共有していただけますか? –

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!'); 
}); 

私はこれをテストするために、今私とnodejsを持っていないが、これはあなたのアイデアを与える必要があります。ルートを定義する必要があります。 .get( "/")を定義していますので、メインURLへのリクエストはすべてこの関数を呼び出します。また、Access-Control-Originを*に設定しました。物事を少しでも保護したい場合は、nodejsから静的ファイルを提供してください。

関連する問題