execute a Nodejs script from an html page?

后端 未结 1 1959
孤城傲影
孤城傲影 2020-12-23 22:16

I am currently using Express.js to create my website. My main server script is called index.coffee. I also created a script called request.js that

相关标签:
1条回答
  • 2020-12-23 22:54

    I use plain JS and not coffee script, so here's an example per Fosco's comment (call it 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);
    

    Write your index.html file, and save it in the /public subfolder of your node app directory (which is exposed above, via 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>
    

    If you're including your request.js as a module, it could be as follows:

    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;
    

    Run node server.js on your server. Then head over to www.yoursite.com/index.html

    0 讨论(0)
提交回复
热议问题