【发布时间】:2019-10-08 04:07:01
【问题描述】:
我想在后端获取客户端的主机域。 例如
- 前端 (http://localhost:3000)
- 后端 (http://localhost:4000)
在前端,使用 ajax 将 api 请求发送到后端。
$.get('http://localhost:4000/auth');
在后端,我确实喜欢这个。
// routes/auth.js
router.get('/', (req, res) => {
console.log(req.headers.referer);
...
});
...
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
当前结果:
undefined
它显示后端网址。
当我做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' }
是不是我做错了什么?请有人帮助我。
【问题讨论】:
-
@Subburaj 是的,主机也是“localhost:4000”
-
我添加了 req.headers
-
尝试:console.log(req.headers.host);
标签: javascript node.js express