解决阿波罗4和GraphQL CORS的问题,可以使用以下代码示例:
const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const cors = require("cors");
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "Hello, world!"
}
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
app.use(cors()); // 处理跨域请求
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);
import ApolloClient from "apollo-boost";
import { ApolloProvider, gql, useQuery } from "@apollo/client";
const client = new ApolloClient({
uri: "http://localhost:4000/graphql",
headers: {
"Access-Control-Allow-Origin": "*", // 允许所有源的跨域请求
// 其他请求头设置...
}
});
const GET_HELLO = gql`
query {
hello
}
`;
function App() {
const { loading, error, data } = useQuery(GET_HELLO);
if (loading) return Loading...
;
if (error) return Error :(
;
return {data.hello};
}
function ApolloApp() {
return (
);
}
这些代码示例演示了如何在阿波罗4和GraphQL中处理CORS问题,使前端和后端能够正常进行跨域请求。
上一篇:阿波罗3分页与字段策略
下一篇:阿波罗本地解析器的位置重要吗?