在使用apollo-server-express时,如果CORS(跨域资源共享)设置不起作用,可以尝试以下解决方法:
npm install cors
const cors = require('cors');
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
const server = new ApolloServer({
// Apollo Server 配置项
});
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);
在上述代码中,我们引入了cors模块并将其作为express中间件使用,这样就可以在Apollo Server上启用CORS。
app.use(cors({
origin: 'http://example.com', // 允许的来源
credentials: true // 允许携带cookie
}));
在以上代码中,我们可以根据实际情况设置origin(允许的来源)和credentials(是否允许携带cookie)。根据需要进行调整以满足项目的CORS需求。
通过以上步骤,你的Apollo Server应该已经启用了CORS,并可以在跨域的情况下正常工作。