【问题标题】:How Do You Configure Create React App to Work with Netlify Lambda Functions如何配置 Create React App 以使用 Netlify Lambda 函数
【发布时间】:2022-08-20 10:10:23
【问题描述】:

我正在尝试将 netlify lambda 函数与创建反应应用程序一起使用,它正在破坏我的网站。

该 repo 是通过运行 npx create-react-app my-app-name 创建的,并且是标准的 create react app 样板。

文件结构:

根目录/package.json

  \"scripts\": {
    \"start\": \"react-scripts start\",
    \"build\": \"react-scripts build\",
    \"test\": \"react-scripts test\",
    \"eject\": \"react-scripts eject\",
    \"lambda\": \"netlify-lambda serve src/lambda\"
  },
  \"devDependencies\": {
    \"netlify-lambda\": \"^2.0.15\"
  }

根目录/netlify.toml:


[build]
  command = \"npm build\" 
  functions = \"lambda\" 
  publish = \"build\"

src/setupProxy.js:


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

module.exports = function (app) {
  app.use(
    proxy(\"/.netlify/functions/\", {
      target: \"http://localhost:9000/\",
      pathRewrite: {
        \"^/\\\\.netlify/functions\": \"\",
      },
    })
  );
};


src/lambda/dictionary.js:

exports.handler = (event, context, callback) => {
  callback(null, {
    statusCode: 200,
    body: \"hello world\",
  });
};

现在,当我尝试运行npm run start 时,应用程序将无法加载。

浏览器显示错误:

This site can’t be reachedlocalhost refused to connect.

当您在浏览器中运行 npm run lambda 并访问 url http://localhost:9000/.netlify/functions/dictionary 时,浏览器会按预期显示“hello, world”。

此外,我无法使用 netlify cli,因为当我尝试安装它时,即使使用 sudo,我也会收到权限错误/访问被拒绝。因此,试图让这种非全局安装的方式工作。

    标签: reactjs lambda create-react-app netlify netlify-function


    【解决方案1】:

    我刚刚遇到了和你的 setupProxy.js 一样的问题, 然后我将 setupProxy.js 修改为下面,它对我有用

    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    module.exports = function(app) {
        app.use(createProxyMiddleware('/functions/', { 
            target: 'http://localhost:9000/', 
            pathRewrite: {
                "^\\.netlify/functions": ""
            }
        }));
    };
    

    【讨论】:

      猜你喜欢
      • 2018-10-06
      • 2016-12-12
      • 2021-11-08
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多