Node.js 被CORS阻止的下一个JS:没有HTTP ok状态

Node.js 被CORS阻止的下一个JS:没有HTTP ok状态,node.js,cors,next.js,apollo,apollo-client,Node.js,Cors,Next.js,Apollo,Apollo Client,我使用GraphQL在客户端和服务器的两个域之间进行通信。我在API网站上启用了CORS,但它似乎抛出了一个被CORS策略阻止的:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态。错误。我在GraphQL中有以下代码: function createApolloClient() { return new ApolloClient({ ssrMode: typeof window === "undefined", link: new HttpL

我使用GraphQL在客户端和服务器的两个域之间进行通信。我在API网站上启用了CORS,但它似乎抛出了一个被CORS策略阻止的
:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态。
错误。我在GraphQL中有以下代码:

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === "undefined",
    link: new HttpLink({
      uri: <link>,
      credentials: "include",
      fetchOptions: {
        mode: "cors",
      },
    }),
  }),
 ...
}

我如何配置我的
next.config.js
文件有什么问题吗?还是阿波罗的客户才是问题所在?我不使用Express。

我通过使用以下配置CORS的其他选项解决了问题:

const allowCors = fn => async (req, res) => {
  res.setHeader('Access-Control-Allow-Credentials', true)
  res.setHeader('Access-Control-Allow-Origin', '*')
  // another common pattern
  // res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
  res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT')
  res.setHeader(
    'Access-Control-Allow-Headers',
    'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
  )
  if (req.method === 'OPTIONS') {
    res.status(200).end()
    return
  }
  return await fn(req, res)
}
我认为这段代码肯定能工作,因为
req.method===OPTIONS
部分的条件是HTTP ok状态,这是请求所缺少的。我使用了API上使用的
apolloServer
处理程序,而不是传递头:

const apolloServer = new ApolloServer({
  schema,
  context: dbConnect(),
});

export const config = {
  api: {
    bodyParser: false,
  },
};

const handler = apolloServer.createHandler({ path: "/api/graphql" }); // THIS
并将其传入并导出
export default allowCors(handler)


感谢@slideshowbarker的灵感

这个
next.config.js
代码显然不足以处理选项请求。Vercel docs的single Node.js Serverless函数部分中的启用CORS显示了如果您以这种方式进行设置,则需要包括对选项请求的特殊处理。因此,如果您在下一个.js应用程序中启用CORS,则可能需要包含类似的内容。
const apolloServer = new ApolloServer({
  schema,
  context: dbConnect(),
});

export const config = {
  api: {
    bodyParser: false,
  },
};

const handler = apolloServer.createHandler({ path: "/api/graphql" }); // THIS