小编典典
我使用普通的JS而非咖啡脚本,因此这是每个Fosco注释(称为server.js)的示例:
var express = require('express'),
list = require('./request.js').Request; // see template
var app = express.createServer();
app.use(express.static(__dirname + '/public')); // exposes index.html, per below
app.get('/request', function(req, res){
// run your request.js script
// when index.html makes the ajax call to /request, this runs
// you can also require your request.js as a module (above) and call on that:
res.send(list.getList()); // try res.json() if getList() returns an object or array
});
app.listen(80);
编写index.html文件,然后将其保存在/public节点应用目录的子文件夹中(通过暴露在上方express.static)。:
Get this List
$(document).ready(function() {
$('#button').click(function() {
// run an AJAX get request to the route you setup above...
// respect the cross-domain policy by using the same domain
// you used to access your index.html file!
$.get('/request', function(list) {
$('#response').html(list); // show the list
});
});
});
如果将 request.js 作为模块包含在内,则可能如下所示:
var RequestClass = function() {
// run code here, or...
};
// ...add a method, which we do in this example:
RequestClass.prototype.getList = function() {
return "My List";
};
// now expose with module.exports:
exports.Request = RequestClass;
node server.js在您的服务器上运行。然后前往/index.html
-07-07