#reactjs #express #cookies #cors #nestjs
#reactjs #экспресс #файлы cookie #cors #nestjs
Вопрос:
Имея сервер nodejs, использующий Nestjs, Express и GraphQL, я настраиваю сервер следующим образом.
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',
})
При локальном запуске server ( 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 из моего веб-приложения на сервер и узнать о CORS в целом. В частности, приветствуются любые подсказки по настройке nestjs GraphQL.
Ответ №1:
Решение заключается в том, что вам нужно передать параметры CORS в GraphqlOptions
, а не в экспресс-конфигурации.