简体   繁体   中英

Correct Approach for Serving Javascript Files via Node.js Ajax?

I am trying to write a node application which serves crjavascript code to a static webpage. The code would then be evaluated in the webpage. Similar to this example , but with node instead of php. Server application looks like this:

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server
var server = http.createServer(function (req, res) {
    var js;
    //send back all libraries
    fs = require('fs');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    //var paths = ['javascript.js'];
    js = fs.readFileSync('example.js').toString();
    res.end('_js(\'{"message": " ' + js + '"}\')');
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// put a message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

While client code looks like this:

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" charset="utf-8"/>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: 'http://127.0.0.1:8000/',
                dataType: "jsonp",
                jsonpCallback: "_js",
                cache: false,
                timeout: 20000,
                success: function(data) {
                    var dataJson = JSON.parse(data);
                    console.log(dataJson['message']);
                    eval(dataJson['message']);
                    alert(test);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('error ' + textStatus + " " + errorThrown);
                }
            });

        });
    </script>
</head>
<body>
    <div class="container" id="container"></div>
</body>
</html>

example.js currently contains one line alert('hello world') . The idea would be to send this line of code to index.html using the ajax query and then run it. However, I keep getting errors based on this line because of the ungainly mess of apostrophes and brackets:

res.end('_js(\'{"message": " ' + js + '"}\')');

I was thinking there must be a better way to do this?

如果您对通过ajax服务javascript并没有严格的要求,那么使用基于节点的Web服务器(例如expressjs)会更简单,这使您可以轻松地服务静态内容

Ok, solved by using res.end('_js(\\'{"message": " ' + escape(js) + '"}\\')'); on the server and eval(unescape(dataJson['message'])) on the client. Apologies for posting but I was getting nowhere for over an hour before figuring a solution...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM