Netlify 函数的 Sapper Rollup 代理配置

Sapper Rollup proxy config for Netlify functions

我正在使用 Sapper Rollup template,但不知道如何将 /.netlify/functions 代理到 localhost:9000。我已经在 setupProxy.js 文件中尝试 http-proxy-middleware 但我不确定在哪里引用该文件,因为 Sapper 开发服务器似乎无法使用 Rollup 配置?

我在 /src/functions/get-code.js 中有一个函数,我正在使用 Netlify lambda 对其进行测试:

package.json

...
"scripts": {
  "dev": "sapper dev",
  "lambda:dev": "netlify-lambda serve src/functions",
  ...

netlify.toml

[build]
  command = "npm run build"
  functions = "lambda"

我可以在 https://localhost:9000/get-code 上测试我的功能,它工作正常。但是,在我的应用程序中,文件 utilities.js 中有一个函数试图向 /.netlify/functions/get-code.

发出请求
export const getCode = (obj) => {
  return axios
    .post('.netlify/functions/get-code', JSON.stringify(obj))
    .then((response) => {
      return response.data
    })
    .catch(function (error) {
      console.error(error)
      return null
    })
}

当我 运行 我的应用程序 (npm run dev) 调用此函数时,它会导致 ECONNREFUSED 错误,因为它正在尝试调用 http:.netlify/functions/get-code.

我曾尝试在 Eleventy 项目中做同样的事情,直到我意识到我不必这样做。不要使用 netlify-lambda 并尝试代理到端口 9000,只需使用 Netlify Dev 即可。

安装 Netlify CLI:

npm install netlify-cli -g

然后 运行 来自项目文件夹的 Netlify Dev:

netlify dev

它将启动您的应用程序并处理您对 /.netlify/functions/get-code 的 http 请求,这样您就可以避免代理问题以及 CORS 问题。