如何与Node.js和Expressasynchronous加载和显示网页内容?

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

无论如何…是否有一些本地技术负载和显示网页内容与Node.js和Expressasynchronous? 是否应该使用XMLHttpRequest对象的目的或存在更好的select?

最好的问候,六。

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

让我们开始我们的要求

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

  • http://localhost:8080 – 我们的node.js / express服务器正在运行
  • www.yahoo.com – 我们希望从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 }); }); }); }); 

这是它,刈,你可以结合这个解决scheme与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 :) } } }); } 

你的问题的第二部分是关于如何在客户端显示数据,我的build议是创build一个iframe并注入原始数据,你会有一些问题的方式(如相对CSS和JavaScript文件path),但我希望你现在有一个起点…

干杯:)

UPDATE

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

我不是100%确定你的问题是什么,但我猜你正在寻找一种方法来获取服务器端数据在客户端的asynchronous请求。

在expression式中 ,在你的路由器中,在你获取了一些数据之后,使用下面的代码发回一个你的javascript可以在客户端使用的JSON对象:

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

学习这个最好的方法可能是谷歌search一个使用你想使用的技术的例子。 例如,我只是谷歌searchExpress Mongoose JSON(其中Mongoose是MongoDB数据库的数据模型),我发现这个: 一个简单的Node.js Web应用程序,它使用Mongoose,Express和MongoDB并返回JSON

除了Express之外,Node还有其他的框架,还有其他的数据库,所以有许多方法可以完成你所要求的。 另外,客户端也有框架来让事情变得更容易,比如JQuery。