首页 > 解决方案 > How to set CORS for two applications running as docker

问题描述

I'm running my frontend application (nextJS) at https://editor.website.com and my backend application (expressJS) at https://api.editor.website.com - both as docker container. I'm trying to upload some image files using graphQL and mostly it works, but sometimes it fails with these two errors:

POST https://api.editor.website.com/graphql 413

Access to fetch at 'https://api.editor.website.com/graphql' from origin 'https://editor.website.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I tried to set universal cors to prevent this problem, but this doesn't work. So what am I missing?

Server

import express from 'express'
import cors from 'cors'

const app = express()
app.options('*', cors())
// app.use(cors())

server.applyMiddleware({ app, path: '/graphql' })

标签: javascriptdockerexpress

解决方案


CORS如果它在大多数情况下都有效,我认为它没有关系(您可能会收到CORS错误,因为如果另一个终止它,您不会点击链中的那个中间件)。据我所知,你收到了413 - Request Entity Too Large

我对 Apollo 服务器端没有太多经验,但您应该根据Apollo API Reference尝试以下操作:

server.applyMiddleware({
    app, path: '/graphql',
    cors: {
        origin: 'https://editor.website.com',
        optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
    },
    bodyParserConfig: {limit: '50mb'} // or your desired limit
})

编辑:

我们在聊天中继续讨论,发现服务前面有一个 nginx 反向代理,它有1MB请求大小的限制。这解决了问题:https ://github.com/jwilder/nginx-proxy/issues/981#issuecomment-345434827


推荐阅读