Dar*_*ier 4 node.js cors apollo next.js apollo-client
我正在使用 GraphQL 在两个域客户端和服务器之间进行通信。我已按照vercel 文档在我的 API 网站上启用了 CORS ,但它似乎引发了blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.错误。我在 GraphQL 中有这样的代码:
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: new HttpLink({
uri: <link>,
credentials: "include",
fetchOptions: {
mode: "cors",
},
}),
}),
...
}
Run Code Online (Sandbox Code Playgroud)
在API网站中,该next.config.js文件有这样的内容:
module.exports = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{
key: "Access-Control-Allow-Origin",
value: <link>,
},
{
key: "Access-Control-Allow-Methods",
value: "GET,OPTIONS,PATCH,DELETE,POST,PUT",
},
{
key: "Access-Control-Allow-Headers",
value:
"X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Access-Control-Allow-Origin",
},
],
},
];
},
};
Run Code Online (Sandbox Code Playgroud)
我的文件配置方式有问题吗next.config.js?或者是 Apollo 客户端出了问题?我不使用快递。
使用最新的 next.js
/api/graphqlimport { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import schema from '../../graphql';
import connectDatabase from '../../graphql/utils/mongoose';
import apiConfig from '../../graphql/utils/config';
import allowCors from '../../utils/cors';
const apolloServer = new ApolloServer({
schema,
introspection: true,
playground: true,
context: async () => {
console.log('context ready');
await connectDatabase(apiConfig.get('mongodb'));
console.log('db connected');
},
});
const handler = startServerAndCreateNextHandler(apolloServer, {
context: async (req, res) => ({ req, res }),
});
export default allowCors(handler);
Run Code Online (Sandbox Code Playgroud)
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;
}
await fn(req, res);
};
export default allowCors;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12019 次 |
| 最近记录: |