apollo-server-express CORS问题

问题描述 投票:3回答:2

所以我正在迁移到apollo-server-express 2.3.3(我使用的是1.3.6)我已经按照几个指南进行了必要的调整,但我遇到了CORS问题。

根据docs,您必须使用applyMiddleware函数将express与apollo服务器连接起来。

我目前正在做以下事情:

const app = express();

// CORS configuration

const corsOptions = {
    origin: 'http://localhost:3000',
    credentials: true
}

app.use(cors(corsOptions))

// Setup JWT authentication middleware

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null"){
        try {
            const currentUser = await jwt.verify(token, process.env.SECRET)
            req.currentUser = currentUser
        } catch(e) {
            console.error(e);
        }
    }
    next();
});

const server = new ApolloServer({ 
    typeDefs, 
    resolvers, 
    context: ({ req }) => ({ Property, User, currentUser: req.currentUser })
});

server.applyMiddleware({ app });


const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
})

出于某种原因,当我尝试从localhost:3000(客户端应用程序)执行请求时,我的快速中间件似乎没有执行,我得到典型的CORS错误

使用apollo-server-express 1.3.6我做了以下操作而没有任何问题:

app.use(
    '/graphql',
    graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
    bodyParser.json(),
    graphqlExpress(({ currentUser }) => ({
        schema,
        context: {
            // Pass Mongoose models
            Property,
            User,
            currentUser
        }
    }))
);

现在使用新版本,事件使文档看起来像一个简单的迁移我似乎并没有使它工作。我检查了各种文章,似乎没有人遇到这个问题。

希望你们能帮助我。

干杯!

node.js express graphql apollo-server
2个回答
9
投票

根据我对Apollo Server middleware API的理解,CORS选项,body-parser选项和graphql端点被视为必须直接传递给applyMiddleware param对象的特殊实体。

所以你想尝试以下配置:

const app = express();

// CORS configuration

const corsOptions = {
    origin: 'http://localhost:3000',
    credentials: true
}
// not needed, CORS middleware is applied
// using the Apollo Server's middleware API
// app.use(cors(corsOptions))

// Setup JWT authentication middleware

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null"){
        try {
            const currentUser = await jwt.verify(token, process.env.SECRET)
            req.currentUser = currentUser
        } catch(e) {
            console.error(e);
        }
    }
    next();
});

const server = new ApolloServer({ 
    typeDefs, 
    resolvers, 
    context: ({ req }) => ({ Property, User, currentUser: req.currentUser })
});

// no need to explicitly define 'path' option in object
// as '/graphql' is the default endpoint
server.applyMiddleware({ app, cors: corsOptions });


const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
})

4
投票

使用Apollo Server 2.x,您可以在cors的构造函数中提供ApolloServer字段。

所以在你的情况下,它应该如下所示:

const corsOptions = {
    origin: 'http://localhost:3000',
    credentials: true
}

// Setup JWT authentication middleware

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null"){
        try {
            const currentUser = await jwt.verify(token, process.env.SECRET)
            req.currentUser = currentUser
        } catch(e) {
            console.error(e);
        }
    }
    next();
});

const server = new ApolloServer({ 
    typeDefs, 
    cors: cors(corsOptions),
    resolvers, 
    context: ({ req }) => ({ Property, User, currentUser: req.currentUser })
});

server.applyMiddleware({ app });


const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
})

在这里,您可以找到apollo服务器接受的所有参数:https://www.apollographql.com/docs/apollo-server/api/apollo-server.html#Parameters-2

在这里您可以找到相关的讨论:https://github.com/apollographql/apollo-server/issues/1142

© www.soinside.com 2019 - 2024. All rights reserved.