【发布时间】: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