1 ajax asynchronous xmlhttprequest node.js express
作为JavaScript和相关框架的初学者,如果我的问题看起来很愚蠢,我很抱歉.
无论如何......是否有一些本地技术用于加载和显示与Node.js和Express异步的网页内容?是否应该将XMLHttpRequest对象用于此目的或存在更好的替代方案?
最好的问候,Vi.
我可以帮你解决问题的第一部分,比如@JohnnyHK说,这是广泛的问题.我将在这里解释的是如何使用node.js加载网页的原始数据并表达并将其发送回json对象内的客户端.
让我们从我们的请求开始
我们的目标是在浏览器中输入以下URL并获取页面的原始数据(html源代码): http://localhost:8080/www.yahoo.com
http://localhost:8080 - 我们的node.js/express服务器正在运行的地方www.yahoo.com - 我们想要从 - http://获取源代码的网站的DOMAIN是不需要的现在,到服务器代码
请注意,这是一个非常简单/基本的服务器,因此您可以更好地改进它
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
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
这就是它,你可以将这个解决方案与a结合使用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 :)
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
你的问题的第二部分是关于如何在客户端显示数据,我的建议是创建一个iframe并将原始数据注入其中,你会遇到一些问题(比如相对的css和javascript文件路径)但是我希望你现在有一个起点......
干杯:)
UPDATE
还有一件事......这个例子只适用于http协议网站...如果你想从https网站获取数据,你需要使用https模块而不是http(var https = require('https');),在options,使用端口443 ......
| 归档时间: |
|
| 查看次数: |
2091 次 |
| 最近记录: |