如何让所有的端口都在原点?

时间:2022-07-27 18:10:32

I have a nodejs server, and i use cors to let my client connect to me.

我有一个nodejs服务器,我使用cors让我的客户端连接到我。

app.use(cors({origin:["http://localhost:3000"]})

I want to allow localhost:1000 or localhost:2000 or 4000, I want it to let localhost to connect no matter what the port is. How can i do it?

我希望允许localhost:1000或localhost:2000或4000,无论端口是什么,我都希望它允许localhost进行连接。我怎么做呢?

1 个解决方案

#1


2  

See the documentation.

见文档。

You can pass a function as the value of origin.

你可以传递一个函数作为原点的值。

  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }   }

Just replace whitelist.indexOf(origin) !== -1 with a regular expression or substring test that matches http://localhost/, optionally followed by any port.

只需将whitelist.indexOf(origin) !== -1替换为与http://localhost/匹配的正则表达式或子字符串测试,可选地后跟任何端口。

e.g.

如。

origin.substring(0, 17) === "http://localhost/";

#1


2  

See the documentation.

见文档。

You can pass a function as the value of origin.

你可以传递一个函数作为原点的值。

  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }   }

Just replace whitelist.indexOf(origin) !== -1 with a regular expression or substring test that matches http://localhost/, optionally followed by any port.

只需将whitelist.indexOf(origin) !== -1替换为与http://localhost/匹配的正则表达式或子字符串测试,可选地后跟任何端口。

e.g.

如。

origin.substring(0, 17) === "http://localhost/";