【问题标题】:How to set an "Access-Control-Allow-Origin" header to only allow one certain computer如何将“Access-Control-Allow-Origin”标头设置为仅允许一台特定计算机
【发布时间】:2020-06-01 09:39:36
【问题描述】:

我在故障服务器中有一些 node.js 代码(不是在我自己的计算机中):

let http = require("http");
http.createServer((req, res) => {
  res.writeHead(200, {
    "Allow-Access-Control-Origin": "http://my-localhost-IP-Address"
  });
  res.end(someData)
})

这似乎对我不起作用。 我无法从我的 localhost 执行此操作,也无法在 file: 协议中执行此操作,但我只需在浏览器中输入 url 即可。

Access-Control-Allow-Origin 设置为http://localhost 也不起作用。

有没有办法可以将“Access-Control-Allow-Origin”标头设置为仅允许某些特定计算机访问它。

注意:同样,代码在互联网的服务器中,而不是在我自己的计算机中。

【问题讨论】:

    标签: node.js http-headers


    【解决方案1】:

    您可以使用 CORS

    let cors = require("cors");
    
    app.use(cors(), function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will make the request from
      res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
      );
      next();
    });
    

    在此,您还可以添加多个 URL。

    【讨论】:

    • 虽然我很欣赏这个答案,但这不会允许来自任何计算机的localhost:4200 吗?
    • 这只是一个例子。我已经添加了评论,请仔细阅读。您已将 IP 地址替换为您要请求的 IP 地址
    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 2016-07-21
    • 2013-09-09
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多