3

我将Gatsbynetlify-lambda一起使用,它为 9000 端口上的函数创建服务器:

http://localhost:9000/myFunctionName

在生产中,函数的地址是:

/.netlify/functions/myFunctionName

所以我想有一个开发模式代理,http://localhost:9000/当我调用/.netlify/functions.

我的自定义 Webpack 配置位于gatsby-node.js

exports.modifyWebpackConfig = ({ config, stage }) => {

  if (stage === 'develop') {

    config.merge({

      devServer: {
        proxy: {
          '/.netlify/functions': {
            target: 'http://localhost:9000',
            pathRewrite: {
              '^/\\.netlify/functions': ''
            }
          }
        }
      }

    })

  }

}

不工作。

我也试过这个https://www.gatsbyjs.org/docs/api-proxy/#api-proxy但我需要重写 url 而不仅仅是前缀。

将netlify-lambdaGatsby一起使用的最佳方法是什么?

谢谢

4

1 回答 1

4

更新: Gatsby 现在确实支持 Express 中间件,在这个合并的 PR中。这将不支持 Webpack Dev Server 代理配置,但允许使用普通的 Express 代理中间件。

要使用netlify-lambda只需将其添加到您的gatsby-config.js

const proxy = require("http-proxy-middleware")

module.exports = {
  developMiddleware: app => {
    app.use(
      "/.netlify/functions/",
      proxy({
        target: "http://localhost:9000",
        pathRewrite: {
          "/.netlify/functions/": "",
        }
      })
    )
  }
}

https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying


不幸的是,Gatsby 开发代理配置根本不可扩展。由于 Gatsby 不使用 webpack 开发服务器,因此它的代理选项不可用。见https://github.com/gatsbyjs/gatsby/issues/2869#issuecomment-378935446

我通过在我的 Gatsby 开发服务器和 netlify-lambda 服务器前面放置一个 nginx 代理来实现这个用例。这是代理服务器配置的一个非常简化的版本(斜杠很重要):

server {
    listen       8001;

    location /.netlify/functions {
        proxy_pass        http://0.0.0.0:9000/;
    }

    location / {
        proxy_pass        http://0.0.0.0:8000;
    }
}

无论如何,我正在使用 nginx 代理,所以这并不是多余的开发设置,但如果 Gatsby 支持这种常见情况肯定会更好。

于 2018-04-05T14:06:03.030 回答