выполнить скрипт Nodejs со страницы HTML? - PullRequest
9 голосов
/ 12 марта 2012

В настоящее время я использую Express.js для создания своего веб-сайта.Мой основной серверный скрипт называется index.coffee.Я также создал скрипт с именем request.js, который делает запрос GET и отображает ответ с

  console.log(list);

. У меня нет проблем при запуске скрипта из консоли: node request.js

MyВопрос в том, как заставить кнопку «Получить этот список» на моей странице реагировать на щелчок, отображая список на той же странице (то есть, выполняя request.js на сервере и показывая результат)?

app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set ('view engine', 'coffee');
app.register('.coffee', require('coffeekup').adapters.express);

  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/', function(req, res) {
  res.render('index',{ layout: false });
});



app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

index.coffee

doctype 5
html ->

  head ->
    body

p -> "эй"

1 Ответ

10 голосов
/ 12 марта 2012

Я использую обычный 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).:

<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 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...