首页 > 解决方案 > 服务器和客户端具有相同的主机(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 发出凭据请求?

标签: javascriptnode.jscorsgraphql

解决方案


您需要在标题中指定实际的 Origin ( http://localhost:3000) 。Access-Control-Allow-Origin

错误消息只是告诉您*不支持通配符 ( )。


推荐阅读