从node.js和express.js中的请求获取客户端域
我想在后端获得客户端的主机域。例如
- 前端(http://localhost:3000)
- 后端(http://localhost:4000)
在前端,使用ajax将api requeset发送到后端。
$.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
它显示后端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' }
我做错了什么吗?请有人帮助我。
回答如下:“引荐请求”标头包含上一个网页的地址,从该网页开始到当前请求的页面的链接。
docs
或者换句话说,单击确定http://localhost:4000
中某个位置的链接,该链接refers到http://localhost:5000
,然后将设置referer
。
或者也许referer
并不是您真正想要的。看看host
。
从node.js和express.js中的请求获取客户端域
我想在后端获得客户端的主机域。例如
- 前端(http://localhost:3000)
- 后端(http://localhost:4000)
在前端,使用ajax将api requeset发送到后端。
$.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
它显示后端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' }
我做错了什么吗?请有人帮助我。
回答如下:“引荐请求”标头包含上一个网页的地址,从该网页开始到当前请求的页面的链接。
docs
或者换句话说,单击确定http://localhost:4000
中某个位置的链接,该链接refers到http://localhost:5000
,然后将设置referer
。
或者也许referer
并不是您真正想要的。看看host
。