【问题标题】:How can I load and display webpage contents asynchronously with Node.js and Express? [closed]如何使用 Node.js 和 Express 异步加载和显示网页内容? [关闭]
【发布时间】:2012-10-15 15:49:25
【问题描述】:

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

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

最好的问候,维。

【问题讨论】:

  • 这不是一个愚蠢的问题,但它太宽泛了。

标签: ajax node.js asynchronous xmlhttprequest express


【解决方案1】:

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

让我们从我们的要求开始

我们的目标是在浏览器中输入如下网址,获取页面的原始数据(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 并将原始数据注入其中,你会遇到一些问题(比如相关的 css 和 javascript 文件路径)但我希望你现在有一个起点......

干杯:)

更新

还有一件事..这个例子只适用于http协议网站...如果你想从https网站获取数据,你需要使用https模块而不是httpvar https = require('https'); ) 并在 options 中,使用端口 443...

【讨论】:

  • 谢谢!为了显示数据,我不会使用 iframe(W3C 不推荐使用的标签)。如何(从客户端)发送请求并在页面中显示相关内容,例如单击按钮或链接?
  • 来自DOMAIN的数据包括htmlheadbody等html标签,所以如果你不作为iframe使用,你就放不下了在常规页面上,如果您删除上面提到的标签,您将丢失重要数据,例如<style /><scripts/>.. 另一种方法是动态构建一个html页面并将数据放入其中,然后您可以重定向客户端到此页面,一个好主意是在动态页面中放置一个fixed 工具栏,以将用户重定向回您的网站...
【解决方案2】:

我不能 100% 确定您的问题是什么,但我猜您正在寻找一种在服务器端获取数据以用于客户端异步请求的方法。

express 中,在您的路由器中,在您检索到一些数据后,使用以下命令发回您的 javascript 可以在客户端使用的 JSON 对象:

res.send(JSON.stringfy(data)); 

了解这一点的最佳方法可能是在 Google 上搜索使用您想要使用的技术的示例。例如,我刚刚在 Google 上搜索 Express Mongoose JSON(其中 Mongoose 是 MongoDB 数据库的数据模型),我发现了这个:A simple Node.js web application that uses Mongoose, Express and MongoDB and returns JSON

Node 有替代框架(Express 除外),还有其他数据库,因此有很多方法可以完成您的要求。此外,客户端也有一些框架可以让事情变得更简单,比如 JQuery。

【讨论】:

    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2011-06-24
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多