ajax - 如何使用 Node.js 和 Express 异步加载和显示网页内容?

标签 ajax node.js asynchronous xmlhttprequest express

作为 JavaScript 和相关框架的初学者,如果我的问题看起来很愚蠢,我很抱歉。

无论如何...是否有一些本地技术可以使用 Node.js 和 Express 异步加载和显示网页内容?应该使用 XMLHttpRequest 对象来达到目的还是存在更好的替代方案?

最诚挚的问候,Vi。

最佳答案

我可以帮助您解决问题的第一部分,就像@JohnnyHK 所说,这是一个广泛的问题。我在这里要解释的是如何使用node.js和express加载网页的原始数据并将其发送回json对象内的客户端。

让我们从我们的请求开始

我们的目标是在浏览器中输入以下URL并获取页面的原始数据(html源):http://localhost:8080/www.yahoo.com

  • http://localhost:8080 - 我们的node.js/express 服务器运行的地方
  • www.yahoo.com - 我们想要从中获取源代码的网站的 DOMAIN - 不需要 http://

现在,到服务器代码

请注意,这是一个非常简单/基本的服务器,因此您最好在自己身边改进它

var http    = require('http');        // the http `native` module of node
var express = require('express');     // the express :)
var app = express();              // creating the server...

app.enable("jsonp callback");         // enable jsonp callbacks
app.listen(8080);                     // listening to port 8080.


app.get('/:domain', function(req, res){  // each request to the pattern `http://localhost:8080/URL_HERE

    // building the http `options` param
var options = {
    host: req.params.domain,     // the host will be the `domain` we sent
    port: 80,                 // the port the website is running on (basically post 80)

    path: '/',                // the path, now, this is important to pages inside
                              // the website, if you want the source of 
                              // `http://www.website.com/path/to/page.html` you better
                              // transfer `/path/to/page.html` as another param to the
                              // request and put it here
    method: 'GET'             // well, you know...
}

var buffer = '';                            // i'm creating a buffer to hold the data
http.get(options, function(httpres){        // creating the request with a callback function
    httpres.setEncoding('utf8');            // setting the encoding for the data...
    httpres.on('data', function(chunk){     // listening to the `data` event, each chunk will get into this function
        buffer += chunk;                    // saving the data...
    });
    httpres.on('end', function(){       // listening to the `end` event will be raised when we got all the raw data
        res.json({                      // this is it, now we are sending a response to the client as a json
            success: true,
            data: buffer
            });
        });
    });
});

就是这样,你可以将此解决方案与 jsonp 结合起来,然后就可以开始了...

客户端

让我们使用 jQuery jsonp 请求来获取数据:

function loadData (domain) {
    $.ajax({
        url: 'http://localhost:8080/' + domain
        cache: false,
        dataType: 'jsonp',
        jsonp: 'callback',
        data: { },
        success: function (response) {
            if(response.success) {
                console.log(response.data); // `response.data` holds the html
                                            // data from the server, do what you want :)
            }
        }
    });
}

你的问题的第二部分是关于如何在客户端显示数据,我的建议是创建一个 iframe 并将原始数据注入(inject)其中,你会遇到一些问题(比如相对的 css 和 javascript 文件路径)但我希望你现在有一个起点......

干杯:)

更新

还有一件事..此示例仅适用于 http 协议(protocol)网站...如果您想从 https 网站获取数据,您需要使用 https 模块而不是 http ( var https = require('https'); ) 并在 options 中,使用端口 443...

关于ajax - 如何使用 Node.js 和 Express 异步加载和显示网页内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899288/

相关文章:

javascript - 一个 grunt 插件如何包装另一个插件

javascript - 在不发出值的情况下完成的 Rxjs 可观察通过单元测试,但不应该

java - 使用 Javascript 和 jOuery 访问 JSON 响应时出错

javascript - 使用 Ajax 调用 Web Api 2 方法

node.js - 不嵌套多次用Mongoose查询

C# 异步,没有任务等待

javascript - html2canvas 等待图片加载

javascript - 如何读取从 ajax 返回的数据数组以获取 google 图表?

ajax - 如何在jQuery中实现多线程

node.js - 为什么 isBuffer 对于不编码的 fs.readFileSync 调用返回 false