如何从服务器端javascript从不同的域获取.txt文件并获取它的客户端

时间:2015-04-10 19:29:35

标签: javascript jquery node.js

我试图从不具有CORS或webservices的其他域上的Web服务器获取.txt文件。我想我需要在Node.js和JQuery的服务器端做这件事,但我不知道从哪里开始。我目前是Node和JQuery的挑战。

该文件位于http://epec.saw.usace.army.mil/dsskerr.txt

1 个答案:

答案 0 :(得分:2)

为此,您需要编写一个Node app服务器端。

var express = require("express"),
    app = express(),
    request = require("request");

var port = process.env.VCAP_APP_PORT || 8080;

app.use(express.static(__dirname + '/public'));

app.listen(port);

app.get("/data", function (req, res) {
    request.get("http://epec.saw.usace.army.mil/dsskerr.txt").pipe(res);
});

在客户端,您可以执行以下操作。

<html>
    <head>
        <title>Simple app to fetch a txt file</title>
    </head>
    <body>
        <h2>simple app to fetch a txt file through a node server to get around CORS</h2>
        <div class="data"> </div>
        <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
        <script>
            $(function() {
                $.get("/data", function(data) {
                    console.log(data);
                    $(".data").append(data);
                });
            });
        </script>
    </body>
</html>

这是一个完整的git repo解决方案。 https://github.com/jsloyer/node-fetch-txt-file

此外,您可以通过单击下面的按钮将解决方案部署到Bluemix。 Deploy to Bluemix