【问题标题】:POST to local json file without server, using Svelte and Routiify使用 Svelte 和 Routiify POST 到没有服务器的本地 json 文件
【发布时间】:2021-09-24 05:48:16
【问题描述】:

我正在使用 Routify 在 Svelte 中编写 PWA,并尝试将注释(包含 id、标题和正文)保存在本地 json 文件中。

我一直在关注 Svelte REPL (Svelte POST example) 的这段代码,但他们使用的是 Web URL。当尝试使用直接链接时,我得到一个 404,即使路径是正确的。

<script>
    let foo = 'title'
    let bar = 'body'
    let result = null
    
    async function doPost () {
        const res = await fetch('https://httpbin.org/post', {
            method: 'POST',
            body: JSON.stringify({
                foo,
                bar
            })
        })
        
        const json = await res.json()
        result = JSON.stringify(json)
    }
</script>


<input bind:value={foo} />
<input bind:value={bar} />
<button type="button" on:click={doPost}>
    <p>Post it.</p>
</button>
<p>Result:</p>
<pre>
{result}
</pre>

我安装了一个 json 服务器插件,有点用,但我想将数据存储为本地文件。

是否可以在不使用任何服务器的情况下使用 POST 写入本地 json 文件? 使用fetch时是否可以使用相对路径?还是我应该使用其他东西?

【问题讨论】:

  • 直接链接是什么意思?你能分享你的代码吗? REPL 很适合参考,但您自己的实现更相关。

标签: json svelte routify


【解决方案1】:

通常,您不会将数据发布到服务器之外的任何其他地方。话虽如此,如果您绝对想使用 POST 保存数据,您可以在您的应用程序中添加一个 serviceworker 来拦截fetch() 请求,然后将数据保存在缓存、indexeddb、localstorage 或类似的东西中。但是让 serviceworker 介于两者之间有点愚蠢,您应该将数据直接存储在缓存、indexeddb 或 localstorage 中。

本地存储示例:

const data = { someKey: { someOtherKey: 'some value' } };
localStorage.setItem('myData', JSON.stringify(data));

但请注意,无论您使用哪种存储,如果用户决定清除浏览器数据或浏览器由于存储不足而自行清理,它们都可能会被清除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2018-08-11
    • 2019-03-20
    相关资源
    最近更新 更多