【发布时间】:2021-02-14 06:08:00
【问题描述】:
拥有一个使用 Nestjs、Express 和 GraphQL 的 nodejs 服务器,我使用以下配置服务器。
GraphqlOptions.ts
@Injectable()
export class GraphqlOptions implements GqlOptionsFactory {
createGqlOptions(): Promise<GqlModuleOptions> | GqlModuleOptions {
return {
context: ({ req, res }) => ({ req, res }),
autoSchemaFile: '/tmp/schema.graphql',
playground: {
endpoint: '/graphql',
},
introspection: true,
cors: {
// Read that we should do this so GraphQL will not override the Express CORS configuration
},
}
}
}
}
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule)
await app.listen(3000)
}
bootstrap()
index.ts
let cachedServer: Server
const bootstrapServer = async (): Promise<Server> => {
const expressApp = express()
expressApp.use(eventContext())
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(expressApp)
)
app.useGlobalPipes(new ValidationPipe())
const corsOptions = {
credentials: true,
origin: [`${process.env.WEB_APP_URL}`],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS'
}
app.enableCors(corsOptions)
app.use(cookieParser())
app.use(helmet())
await app.init()
return createServer(expressApp)
}
export const handler: APIGatewayProxyHandler = async (event, context) => {
if (!cachedServer) {
cachedServer = await bootstrapServer()
}
return proxy(cachedServer, event, context, 'PROMISE').promise
}
并在 Reactjs 应用程序中使用以下内容配置 Apollo 客户端。
private readonly httpLink = createHttpLink({
uri: 'https://theserver.yyy',
credentials: 'include',
fetch,
fetchOptions: {
credentials: 'include'
}
})
private readonly authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: this.accessToken ? `Bearer ${this.accessToken}` : '',
},
}
})
this.apolloClient = new ApolloClient({
cache: this.cache,
link: this.authLink.concat(this.httpLink),
connectToDevTools: true,
credentials: 'include',
})
当在本地运行服务器 (localhost:4000) 和 Reactjs 应用程序 (localhost:3000) 时,一切正常,但从技术上讲,两者都来自同一个来源 (localhost),当应用程序部署时,服务器是 (theserver.yyy) 域和 reactjs (thewebap.ddd) 域结果在 Chrome 浏览器中收到以下内容。
Access to fetch at 'https://theserver.yyy/graphql' from origin 'https://thewebap.ddd' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
和使用 Firefox 类似。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://theserver.yyy/graphql. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).
CORS 在AWS API Gateway 中启用。我很感激一些指导来学习如何允许 CORS 从我的 web 应用程序到服务器并了解一般的 CORS。具体来说,任何配置 nestjs GraphQL 的提示都值得赞赏。
【问题讨论】:
标签: reactjs express cookies cors nestjs