我正在尝试编写一个节点应用程序,它将crjavascript代码提供给一个静态网页。代码将在网页中进行评估。类似于this example,但用节点而不是php。服务器应用程序是这样的:通过Node.js Ajax提供Javascript文件的正确方法?
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server
var server = http.createServer(function (req, res) {
var js;
//send back all libraries
fs = require('fs');
res.writeHead(200, {'Content-Type': 'text/plain'});
//var paths = ['javascript.js'];
js = fs.readFileSync('example.js').toString();
res.end('_js(\'{"message": " ' + js + '"}\')');
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// put a message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
虽然客户端代码如下所示:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" charset="utf-8"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:8000/',
dataType: "jsonp",
jsonpCallback: "_js",
cache: false,
timeout: 20000,
success: function(data) {
var dataJson = JSON.parse(data);
console.log(dataJson['message']);
eval(dataJson['message']);
alert(test);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus + " " + errorThrown);
}
});
});
</script>
</head>
<body>
<div class="container" id="container"></div>
</body>
</html>
example.js目前包含一行alert('hello world')
。这个想法是使用ajax查询将这行代码发送到index.html,然后运行它。不过,我不断收到因为撇号和括号的丑陋混乱的基础上这一行错误:
我想必须有一个更好的方式来做到这一点?
res.json()如果你不介意使用Express,或者JSON.stringify? – 2013-02-09 23:09:24