node.js require 自动执行脚本 并生成html,从HTML页面执行Nodejs脚本?

小编典典

我使用普通的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 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)。:

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('http://www.yoursite.com/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在您的服务器上运行。然后前往www.yoursite.com/index.html

2020-07-07

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值