【问题标题】:Get client domain from request in node.js & express.js从 node.js 和 express.js 中的请求中获取客户端域
【发布时间】:2019-10-08 04:07:01
【问题描述】:

我想在后端获取客户端的主机域。 例如

在前端,使用 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


【解决方案1】:

Referer 请求标头包含前一个网页的地址,从该网页链接到当前请求的页面。

docs

或者换句话说,在http://localhost:4000 中的某处点击确定引用http://localhost:5000 的链接,然后referer 将被设置。

或者referer 并不是您真正想要的。看看host

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多