Blog | G5 Cyber Security

Website to Localhost HTTP Requests

TL;DR

A website can make an HTTP request to localhost, but it’s tricky due to the browser’s security features (the same-origin policy). Common workarounds include using a proxy server on your web server or enabling CORS (Cross-Origin Resource Sharing) on the localhost service. The best approach depends on what you’re trying to achieve.

Why it’s normally blocked

Browsers have a security feature called the same-origin policy. This means a web page can only make requests to the same domain (protocol, host, and port) as the page itself. This prevents malicious websites from stealing data from other sites you’re logged into.

localhost is considered a different origin than most publicly hosted websites. Therefore, direct requests are blocked by default.

How to make it work

  1. Using a Proxy Server
const express = require('express');
const httpProxy = require('http-proxy');

const app = express();
const proxy = httpProxy.createProxyServer({});

app.all('*', (req, res) => {
  proxy.web(req, res, { target: 'http://localhost:3000' }); // Replace 3000 with your localhost port
});

app.listen(8080, () => console.log('Proxy server listening on port 8080'));
  • In this example, all requests to your web server (port 8080) are proxied to localhost:3000.
  • Enabling CORS
  • const express = require('express');
    const cors = require('cors');
    
    const app = express();
    app.use(cors()); // Enable CORS for all routes
    
    app.get('/data', (req, res) => {
      res.json({ message: 'Data from localhost' });
    });
    
    app.listen(3000, () => console.log('Server listening on port 3000'));
  • This example enables CORS for all routes on the localhost server.
  • JSONP (Older Method – Limited)
  • Browser Extensions
  • Important Considerations

    Exit mobile version