【问题标题】:CORS settings are ignoredCORS 设置被忽略
【发布时间】:2019-08-07 21:47:52
【问题描述】:

我在使用 node.js 时遇到问题,显然忽略了我的 cors 设置。 这是我的回购: Backend Frontend

后端的罪魁祸首代码:

...
//config.CLIENT_URL is 'http://localhost:3000'

const corsOptions: cors.CorsOptions = {
        origin: [String(config.CLIENT_URL)],
        credentials: true,
    };
    app.use(cors(corsOptions));
...

Apollo 实现

//config.BACKEND_URL_DEV is 'http://localhost:4000/graphql/'
function create (initialState, { getToken }) {
  const httpLink = createHttpLink({
    credentials: "include",
  uri: `${config.BACKEND_URL_DEV}`,
  })

  const authLink = setContext((_, { headers }) => {
    let token = getToken()
    return {
      headers: {
        ...headers,
        cookie: token ? token : ''
      }
    }
  })

  return new ApolloClient({
    connectToDevTools: process.browser,
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    link: authLink.concat(httpLink),
    cache: new InMemoryCache().restore(initialState || {})
  })
}

当我转到http://localhost:3000/dashboard 时,如果我通过graphql playground 登录,我知道我会执行我的查询,这是我收到的消息:

收到了足够有趣的数据,但 CORS 阻止它显示。 在 Opera、Chrome 和 Firefox DevEdition 上测试

如果请求源域正确,我的后端似乎将* 设置为Access-Control-Allow-Origin

非常感谢您对此事的任何见解!

【问题讨论】:

  • 尝试执行console.log(cors(corsOptions)) 并检查所有值以确保一切设置正确
  • 返回[Function: corsMiddleware] 但我找到了解决方案!
  • 作为答案发布
  • 谢谢@evgenifotia,你让我走上了正轨!

标签: node.js cors apollo-client next.js


【解决方案1】:

原来问题在于将cors 配置传递给apollo-server-express,因为app.use(cors(corsOptions)) 对于这种设置实际上没有任何作用。

正确答案: 将 cors 配置移至此部分:

apolloServer.applyMiddleware({ app, cors: corsOptions });

感谢stack thread找到答案

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2014-06-25
    • 2015-04-14
    相关资源
    最近更新 更多