fetch() post 404 错误

fetch() post 404 error

我正在为 node.js 应用编写一个简单的 preact 前端。我正在尝试从项目目录中的 json 文件读取数据,从用户那里获取一些输入,然后将其写回文件。

我可以使用 fetch() 从我的项目目录加载 json 文件...

fetch('config.json');

...但是当我将数据写回文件时,我收到 404...

fetch('config.json', {
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify(this.state)
});

知道为什么这不起作用吗?

一个 post 请求需要由您的服务器处理,所以您不能直接 post 到一个文件。

如果您使用的是 Express,则可以为此创建路线。类似于:

app.post('/post-data', function(request, response){
  // get data and write to the file here
})

参见:http://expressjs.com/en/api.html#app