Categories
JavaScript Answers

How to get the domain originating the request in Express.js and JavaScript?

Spread the love

Sometimes, we want to get the domain originating the request in Express.js and JavaScript.

In this article, we’ll look at how to get the domain originating the request in Express.js and JavaScript.

How to get the domain originating the request in Express.js and JavaScript?

To get the domain originating the request in Express.js and JavaScript, we use the host or origina headers or the req.socket.remoteAddress to get the IP address that the request originates from.

For instance, we write

const host = req.get("host");

to get the host header value.

We use

const origin = req.get("origin");

to get the origin header value, which has the host of the originating request for CORS requests.

We get the IP address of the originating request with

const userIP = req.socket.remoteAddress;

req is the request parameter in our route handler or middleware.

Conclusion

To get the domain originating the request in Express.js and JavaScript, we use the host or origina headers or the req.socket.remoteAddress to get the IP address that the request originates from.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *