3

Lets say, I have a server running at: https://example.com The code in server:

const express = require("express");
const app = express();

app.get('/',(req, res)=>{
  let data = {'Hello':'World'}
  res.json(data);
});

app.post('/',(req, res)=>{
  let name = req.body.name;
  let email = req.body.email;
  res.json({name, email});
});

app.listen(3000);

Now, there is a client: https://website.com, trying to access server response by making a GET and POST request. (No API key is required)

How can the server find the web address of the client? In this example, I want the server (example.com) to determine the client's URL (website.com) and save it in the database. req.hostname() is not giving the desired output..

  • possibly the answer is here https://stackoverflow.com/questions/18498726/how-do-i-get-the-domain-originating-the-request-in-express-js – Anubrij Chandra Jul 01 '20 at 07:36
  • Does this answer your question? [Express.js: how to get remote client address](https://stackoverflow.com/questions/10849687/express-js-how-to-get-remote-client-address) – Tirolel Jul 01 '20 at 07:36
  • Thank you. I read those Posts before posting this question. I didn't get the desired output. – newcoaderzz Jul 01 '20 at 07:40

1 Answers1

2

req.hostname is what you're looking for.

Update:

After re-reading your question, I think what you want is identifying cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72