我一个人为此奋斗了一段时间。
尝试下一种方法:
const express = require('express');
const { introspectSchema, makeRemoteExecutableSchema, ApolloServer } = require('apollo-server-express');
const { HttpLink } = require('apollo-link-http');
const fetch = require('node-fetch');
const { setContext } = require('apollo-link-context');
async function runServer() {
const httpLink = new HttpLink({ uri: 'http://remote.graphql.server:5555/graphql', fetch });
const link = setContext((request, prevContext) => {
if (prevContext.graphqlContext && prevContext.graphqlContext.headers) {
return {
headers: {
'Authorization': prevContext.graphqlContext.headers.authorization,
}
}
} else {
return {}
}
}).concat(httpLink);
const schema = await introspectSchema(link);
const executableSchema = makeRemoteExecutableSchema({
schema,
link,
});
const server = new ApolloServer({
schema: executableSchema,
context: ({ req }) => ({
headers: req.headers
}),
});
// middleware
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(
'ð Server ready at localhost:4000',
)
)
}
runServer();