简体   繁体   中英

nodejs equivalent of php code involving $_GET and file_get_contents

Can you tell me what is the node.js equivalent of this code:

<?php
    $url = $_GET['url'];
    $html = file_get_contents($url);
    echo $html;
?>

The reason I want to be able to do this, is because I want to open an external domain page in an iframe and be able to manipulate the DOM inside the iframe without encounter same domain policy .

Thanks!

@BrandomWamboldt is correct, you simply can't access the other domain's DOM.

As a workaround, you can have your own server download that page and manipulate the DOM. That way you can serve the page from a URL on your domain.

That's not to say it's a good idea, since you're allowing the other site to inject scripts that you pass on to your users. But here's an example of changing another site's page and sending the response from your own domain, using jsdom :

var jsdom = require('jsdom');
function handler(req, res){
  jsdom.env(
    "http://stackoverflow.com/questions/19254525/php-echo-equivalent-in-node",
    ["http://code.jquery.com/jquery.js"],
    function (errors, window) {
      window.$('body').prepend(
        window.$('<h1></h1>').text('Text inserted by Node')
      );
      var doc = window.document;
      var output = doc.doctype.toString()+doc.innerHTML;
      res.setHeader('Content-Type', 'text/html');
      res.writeHead(200);
      res.end(output);
    }
  );
};
require('http').createServer(handler).listen(3000);

If you don't care about a DOM on the server side you may be able to simply download the entire remote page with http.request or the request library, then send the page contents as the response from your domain.

And again this is bad from a security standpoint so you should probably look for alternative solutions

partial equivalent is

function h(req, res){
  var query = require('url').parse(req.url,true).query;
  var data = require('url').parse(query.url);
  require('http').request({
    host: url.host,
    path: url.pathname
 }, function(response){
   response.on('data', function (chunk) {res.write(chunk);});
   response.on('end', function () { res.end(); });
 })
}
require('http').createServer(h).listen(80);

res.write here sends data to the browser sure you can store all it in some variable and put it to your own template

Upd: add using get parameter url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM