Search code examples
node.jsexpressmiddlewarenode-http-proxy

How to access website content from onother server with express or http


How to access website content from another server with Express or HTTP

I have a website that holds all data like template website for example

and I have 3 more websites that get access this website template content HTML CSS everything inside website 2 3 and 4 the only defriend is the route like

mysite.com/template1/user1/index.html

mysite.com/template1/user2/index.html

mysite.com/template1/user3/index.html

I want to have inside website **(n)* only code that gets the HTML CSS and js content from the template server the master how I can do that?.

In PHP is something like

$url = $GET(www.masterserve.com/template1/ + user1 ) echo $url

Any example that I can do the same with node.js and express

// Get dependencies

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our API routes
const api = require('./server/routes/api');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist'))); <-- idont want static 
file only a URL from the master server

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

Solution

  • If you're trying to get HTTP content from some other server from within your nodejs app, you can use the request module.

    request.get('http://somesite.com/template1/user3/index.html', function(err, response, body) {
        // access data from other web site here
    });
    

    If you're trying to stream that data to some other response, you can also .pipe() the data that you requested to another response. The documentation for that module shows lots of examples of how to do that.