从后端的node.js和express.js中的请求获取客户端域名
我想在后端获得客户端的主机域。例如
- 前端(http://localhost:3000)
- 后端(http://localhost:4000)
在前端,使用ajax将api请求发送到后端。
$.get('http://localhost:4000/auth');
在后端,我确实喜欢这个。
// routes/auth.js
router.get('/', (req, res) => {
console.log(req.headers.host);
...
});
...
module.exports = router;
这是我的后端app.js
。
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);
...
预期结果:
localhost:3000
当前结果:
localhost:4000
它显示后端URL。
当我完成console.log(req.headers)时,如下所示。
- 邮递员的请求
{ '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' }
我做错了什么吗?请有人帮助我。
回答如下:创建自定义标头'xyz'或您选择的任何名称,并在发送请求时在客户端分配URL。在服务器访问中,就像req.get('xyz')。
[已经有了可用的东西,我无法获得端口。
req.protocol + '://' + req.host + req.originalUrl
从后端的node.js和express.js中的请求获取客户端域名
我想在后端获得客户端的主机域。例如
- 前端(http://localhost:3000)
- 后端(http://localhost:4000)
在前端,使用ajax将api请求发送到后端。
$.get('http://localhost:4000/auth');
在后端,我确实喜欢这个。
// routes/auth.js
router.get('/', (req, res) => {
console.log(req.headers.host);
...
});
...
module.exports = router;
这是我的后端app.js
。
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);
...
预期结果:
localhost:3000
当前结果:
localhost:4000
它显示后端URL。
当我完成console.log(req.headers)时,如下所示。
- 邮递员的请求
{ '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' }
我做错了什么吗?请有人帮助我。
回答如下:创建自定义标头'xyz'或您选择的任何名称,并在发送请求时在客户端分配URL。在服务器访问中,就像req.get('xyz')。
[已经有了可用的东西,我无法获得端口。
req.protocol + '://' + req.host + req.originalUrl