请求开发模式localhost中的Next.js应用程序在不同端口上运行的Graphql API

我目前切换现有的应用程序从创build反应应用程序到next.js,似乎一切正常工作,除了我的API端口运行在另一个节点应用程序在端口4000,我无法从我的next.js应用程序。 我跟着回购的例子,但我不能使它的工作,在生产中我使用nginx作为反向代理没有问题,但我在开发模式。 为了设置与Redux的阿波罗我跟着这个例子: with-apollo-and-redux和代理我用这个例子与自定义反向代理

我知道,我做错了,我现在还搞不清楚

在initApollo.js中

... function create() { return new ApolloClient({ ssrMode: !process.browser, networkInterface: createNetworkInterface({ uri: "/api" }) }); } ... 

在server.js中

 ... const devProxy = { "/api/": { target: "http://localhost:4000/api/", changeOrigin: true } }; app .prepare() .then(() => { const server = express(); if (dev && devProxy) { const proxyMiddleware = require('http-proxy-middleware') Object.keys(devProxy).forEach(function (context) { server.use(proxyMiddleware(context, devProxy[context])) }) } server.all("*", (req, res) => handle(req, res)); server.listen(3000, err => { if (err) throw err; console.log("> Ready on http://localhost:3000"); }); }) .catch(ex => { console.error(ex.stack); process.exit(1); }); 

好吧,我终于find了与Next.js或Apollo客户端无关的问题。 但相反,这是关于我的服务器上运行的端口4000(我的graphql服务器)。 我不得不处理CORS,并且我认为默认情况下不支持express express-graphql

所以我添加以下到我的服务器运行graphql

 app.use("/api", function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With" ); if (req.method === "OPTIONS") { res.sendStatus(200); } else { next(); } }); 

也在阿波罗客户端,我不得不放弃绝对path到我的api服务器

 networkInterface: createNetworkInterface({ uri: "http://localhost:4000/api/" }) 

而已