Reputation: 657
I'd like to get a client's host domain on backend side. e.g.
On frontend side, send api request to backend using ajax.
$.get('http://localhost:4000/auth');
On backend side, I did like this.
// routes/auth.js
router.get('/', (req, res) => {
console.log(req.headers.host);
...
});
...
module.exports = router;
this is my app.js
in backend.
const express = require('express');
const app = express();
const authRoutes = require('./routes/auth.js');
...
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', authRoutes);
...
Expected result:
localhost:3000
Current result:
localhost:4000
It shows backend url.
When I did console.log(req.headers), it's the following.
{ 'user-agent': 'PostmanRuntime/7.17.1',
accept: '*/*',
'cache-control': 'no-cache',
'postman-token': '5eb5791e-3a5a-4285-83c9-33320d935a2e',
host: 'localhost:4000',
'accept-encoding': 'gzip, deflate',
cookie:
'connect.sid=s%3A5DIRzqn5HVL3vra410YJ6I56uo9qIj2M.6OWL8rKr1peEMz60sakejaeJJNgv5LQFUKypA6cCXLQ',
connection: 'keep-alive' }
{ host: 'localhost:4000',
accept: '*/*',
'content-type': 'application/json' }
Is there something I did wrong? Please someone help me.
Upvotes: 1
Views: 2377
Reputation: 946
It is not possible to receive the clients current URL as this is not inlcuded by default in the request header. The host
header is pointing the target domain the request is intended for and not the current URL of the client application.
Instead, you need to add the current URL, also here called window.location
to your request by defining a custom header:
// please be aware, that according to the documentation, you cannot use `$.get(...)` here. Use https://api.jquery.com/jQuery.ajax/ instead.
$.ajax({
url: "http://localhost:4000/auth",
headers: {"X-Window-Location": window.location}
});
And on the backend side:
router.get('/', (req, res) => {
console.log(req.headers['X-Window-Location']);
...
});
Upvotes: 0
Reputation: 1759
create a custom header 'xyz' or any name of your choice and assign the url in client side while sending the request. In server access it like req.get('xyz').
with already available stuff, I wasn't able to get port.
req.protocol + '://' + req.host + req.originalUrl
Upvotes: 1