[英]Express CORS subdomain
I have a site — https://example.com
— that makes calls to an API — https://api.example.com
—. 我有一个网站
https://example.com
://example.com-可以调用API- https://api.example.com
。 The API is written in Express, and its using CORS package to allow the requests from the site: 该API是用Express编写的,并且使用CORS包来允许来自站点的请求:
app.use(
cors({
credentials: true,
origin: "https://example.com",
})
);
The site can be accessed via https://example.com
or via https://www.example.com
. 可以通过
https://example.com
或https://www.example.com
访问该网站。 As you see, in the API am allowing explicitly the requests coming from the former address, but not from the latter. 如您所见,在API中,显式允许来自前者地址的请求,但不允许来自后者的请求。 So if anyone access it via the latter address the requests to the API will be rejected.
因此,如果有人通过后一个地址访问它,则对该API的请求将被拒绝。
What is the usual way to solve that? 解决该问题的通常方法是什么? Allow explicitly both
https://example.com
and https://www.example.com
? 明确允许
https://example.com
和https://www.example.com
吗? Or maybe there is a way to ignore the subdomain www
? 或者,也许有一种方法可以忽略子域名
www
?
Thanks in advance! 提前致谢!
-- -
EDIT: 编辑:
As proposed I added https://www.example.com
explicitly to the cors configuration 按照建议,我将
https://www.example.com
明确添加到cors配置中
app.use(
cors({
credentials: true,
origin: ["https://example.com", "https://www.example.com"],
})
);
But this didn't work. 但这没有用。 As a workaround what I just did is to redirect with a rewrite condition in
.htaccess
file —Apache server— from www
domain to non www
domain. 作为一种解决方法,我刚刚执行的操作是将
.htaccess
文件(Apache服务器)中的重写条件从www
域重定向到非www
域。
But the question now is: why even allowing www.example.com
didnt work? 但是现在的问题是:为什么连
www.example.com
没有用? Is there any common reason for that? 有什么共同的原因吗?
The usual way would be to avoid having two websites on different origins with identical content. 通常的方法是避免两个不同来源的网站具有相同的内容。
Configure www.example.com
to issue an HTTP 301 redirect to example.com
. 配置
www.example.com
以发出HTTP 301重定向到example.com
。
Allow explicitly both
https://example.com
andhttps://www.example.com
?明确允许
https://example.com
和https://www.example.com
吗?
That would work too. 那也可以。
origin
can be passed an array. origin
可以传递一个数组。
Or maybe there is a way to ignore the subdomain www?
或者,也许有一种方法可以忽略子网域www?
origin
can also be passed a regular expression. origin
也可以传递正则表达式。
You need to allow both domains. 您需要同时允许两个域。 The API for doing this is a bit complicated.
用于执行此操作的API有点复杂。 Basically you need to read the documentation of the CORS package :
基本上,您需要阅读CORS软件包的文档 :
app.use(
cors({
credentials: true,
origin: function (origin callback) {
switch (origin) {
case "https://example.com":
case "https://www.example.com":
callback(null, true); // allow these domains
break;
default:
callback(new Error('Now allowed')); // block others
}
},
})
);
The value of origin
can only be either a string or your own custom logic implemented as a function. origin
的值只能是字符串或实现为函数的您自己的自定义逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.