node.js - 在本地主机开发模式下从 Next.js 应用程序请求在不同端口上运行的 Graphql api

标签 node.js express react-apollo apollo-client next.js

我目前正在将我现有的应用程序从 create-react-app 切换到 next.js, 一切似乎都正常工作,除了我的 api 端点在端口 4000 上的另一个 Node 应用程序上运行,我无法从我的 next.js 应用程序访问它。 我按照 repo 协议(protocol)中的示例进行操作,但我无法使其工作, 在生产中我使用 nginx 作为反向代理没有问题,但我处于开发模式。 为了使用 Redux 设置 Apollo,我遵循了这个例子:with-apollo-and-redux对于代理,我使用了这个例子 with-custom-reverse-proxy

我知道,我做错了什么,我只是暂时想不通

在 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);
      });

最佳答案

好的,我终于找到了与 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();
  }
});

而且在 apollo 客户端中,我必须将绝对路径放入我的 api 服务器

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

就是这样

关于node.js - 在本地主机开发模式下从 Next.js 应用程序请求在不同端口上运行的 Graphql api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904060/

相关文章:

node.js - 使用 Node.JS 调用 AWSglue 的 lambda 函数没有 console.log 的原因是什么?

node.js - Express JS 对查询结果返回 null,并在使用 pgAdmin 查询时显示值

reactjs - 当查询包含边和节点时,如何使用 Apollo 更新查询?

javascript - 如何在 JavaScript 中获取 Application Insights 操作 id?

node.js - 在 Azure Functions 上部署 Node 应用程序

node.js - 如何从 Node 服务器发送 Firebase 云消息?

node.js - 静态提供 JS 文件,包括使用 Express 的 Node 应用程序中的 Node 模块,以及客户端与服务器端编程

mysql - 如何在nodejs中处理Promise

reactjs - 初始化后更新 ApolloClient header

redux - 如何将 Gatsby 混合站点连接到 Apollo/Graphcool(或 Redux)?