javascript - 服务器和客户端具有相同的主机(localhost),但端口不同(8080、3000)。我可以使用 Access-Control-Allow-Credentials: true 吗?
问题描述
我的服务器在 localhost:8080 上运行。我的客户端在 localhost:3030 上运行。我想使用 httponly cookie 设置刷新令牌来管理 JWT 访问令牌的刷新和到期。
我的服务器代码如下所示
app.use(
cors({
origin:
process.env.NODE_ENV === "production"
? "abc.com"
: "localhost:3000",
credentials: true
})
);
apolloServer.applyMiddleware({ app, path: "/graphql" });
在客户端,我有
const link = createHttpLink({
uri: `localhost:8080/graphql`,
credentials: "include"
});
const client = new ApolloClient({
cache: new InMemoryCache(),
link
});
正如预期的那样,我收到了这个错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/graphql. (Reason: CORS request did not succeed).
我希望这是因为我正在从 localhost:3000 发出请求到 localhost:8080。
现在,如果我更改为允许使用任何来源*
,
app.use(
cors({
origin: process.env.NODE_ENV === "production" ? "abc.com" : "*",
credentials: true
})
);
我明白了Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://localhost:8080/graphql’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).
那么我有什么选择呢?当我在不同端口上运行服务器和客户端时,是否无法使用 httponly cookie 发出凭据请求?
解决方案
您需要在标题中指定实际的 Origin ( http://localhost:3000
) 。Access-Control-Allow-Origin
错误消息只是告诉您*
不支持通配符 ( )。
推荐阅读
- python - gem5 "ImportError: No module named Six" 即使安装了模块六
- tcp - TCP 可靠服务
- c++ - C++:右值引用构造函数和复制省略
- ffmpeg - 使用FFmpeg重新编码时如何获得视频无损旋转?
- airflow - 为什么我的 Airflow DAG 没有运行完成?
- github - 谁可以转让回购所有权
- python - SQLITE3 python根据字符串日期yyyy/mm/dd hh:mm:ss删除行
- wordpress - 我想知道如何让这个 CSS 只在 Woocommerce 上的某些产品上工作?
- c++ - 如何在 C++ 中创建 if else 循环而不是多个嵌套?
- nfc - 读取 NFC 标签时如何显示标题而不是 URL