我使用普通的JS而非咖啡脚本,因此这是每个Fosco注释(称为
server.js)的示例:
var express = require('express'), list = require('./request.js').Request; // see templatevar app = express.createServer();app.use(express.static(__dirname + '/public')); // exposes index.html, per belowapp.get('/request', function(req, res){ // run your request.js script // when index.html makes the ajax call to www.yoursite.com/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)。:
<html> <body> <div id="button">Get this List</div> <div id="response"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(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('http://www.yoursite.com/request', function(list) { $('#response').html(list); // show the list }); }); }); </script> </body</html>
如果将 request.js 作为模块包含在内,则可能如下所示:
var RequestClass = function() { // run pre 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在您的服务器上运行。然后前往
www.yoursite.com/index.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)