如何使用 Svelte 处理 Netlify 函数?

How can I address a Netlify function with Svelte?

我写了一个 vanilla html 应用程序来测试 Netlify 函数并且它有效

我试图编写一个 Svelte 应用程序来模拟相同的功能

两个版本的目录结构基本相同,只是将App.svelte替换为index.html

在 Svelte 版本中,当我尝试访问 hello.js 时出现 404 错误。我假设我没有为 Svelte 中的函数提供正确的路径,但它应该是什么?

.
├── netlify
│   └── functions
│       └── hello.js
├── netlify.toml
├── package.json
├── package-lock.json
├── public
│   ├── build
│   │   ├── bundle.css
│   │   ├── bundle.js
│   │   └── bundle.js.map
│   ├── favicon.png
│   ├── global.css
│   └── index.html
├── README.md
├── rollup.config.js
├── scripts
│   └── setupTypeScript.js
└── src
    ├── App.svelte
    └── main.js

我在基本目录中有运行以下脚本

npm install netlify-cli netlify-lambda

netlify link

package.json

{
"name": "svelte-app",
"version": "1.0.0",
"private": true,
"scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public --no-clear"
},
"devDependencies": {
    "@rollup/plugin-commonjs": "^17.0.0",
    "@rollup/plugin-node-resolve": "^11.0.0",
    "rollup": "^2.3.4",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.0.0",
    "rollup-plugin-terser": "^7.0.0",
    "svelte": "^3.0.0"
},
"dependencies": {
    "netlify-cli": "^10.3.0",
    "netlify-lambda": "^2.0.15",
    "sirv-cli": "^2.0.0"
}
}

netlify.toml

[dev]
publish = "src"

App.svelte

<main>
    <h1>Netlify/Svelte</h1>

    <p>function result: <span id="function-result"></span></p>
</main>

<script>
    async function callHello() {
        const url = `/.netlify/functions/hello`;

        try {
            const response = await fetch(url);
            const data = await response.json();

            console.log('Data returned by function:', data)
            let display = document.getElementById('function-result')
            display.innerText = data
            return data;
        } catch (err) {
            console.log(err);
        }
    }
    callHello()
</script>

netlify/functions/hello.js

exports.handler = async (event, context) => {
    return {
        statusCode: 200,
        body: JSON.stringify('Hola Mundo')
    }
}

我的 package.json 中的 sirv-cli 版本似乎有问题,它停止了Netlify 服务器正确启动

应该是

"dependencies": {
    ...
    "sirv-cli": "^1.0.11"
}