首页 > 解决方案 > 如何在 CRUD 应用程序中正确更新

问题描述

我正在使用 webpack 作为模块捆绑器和 json:server 作为模拟后端的 CRUD 应用程序。所有其他操作都运行良好,但更新将字段填充为未定义。所以如果一个帖子如下......

Post 1

content for post 1

如果我尝试对其进行编辑,它将按字面意思显示...

Undefined

Undefined

我不确定我在哪里出错了,但我认为这是一个范围问题。我要么没有正确引用某些东西,要么我需要重新考虑一组花括号。至少我是这么认为的。

在我的http.js文件中,put 请求与所有其他请求(post、put、delete、get)一起在一个 HTTP 类中

...
    // Make an HTTP PUT Request
    async put(url, data) {
        const response = await fetch(url, {
            method: 'PUT',
            headers: {
                'Content-type': 'application.json'
            },
            body: JSON.stringify(data)
        });

        const resData = await response.json();
        return resData;
    }

...

上面的代码被导出到处理提交发布功能的app.js文件中。

...
function submitPost() {
    const title = document.querySelector('#title').value;
    const body = document.querySelector('#body').value;
    const id = document.querySelector('#id').value;

    const data = {
        title,
        body
    }

    // Validate input
    if (title === '' || body === '') {
        ui.showAlert('Please fill in all fields', 'alert alert-danger');
    } else {
        // Check for ID
        if (id === '') {
            // Create Post
            http.post('http://localhost:3000/posts', data)
                .then(data => {
                    ui.showAlert('Post added', 'alert alert-success');
                    ui.clearFields();
                    getPosts();
                })
                .catch(err => console.log(err));
        } else {
            // Update Post
            http.put(`http://localhost:3000/posts/${ id }`, data)
                .then(data => {
                    ui.showAlert('Post updated', 'alert alert-success');
                    ui.changeFormState('add');
                    getPosts();
                })
                .catch(err => console.log(err));
        }

    }
}
...

据我所知,从 ui 模块导入的 ui 函数都可以正常工作。getPosts 也可以工作,但如果有必要查看它或 HTML 文件,我很乐意提供它。任何帮助将不胜感激。

编辑:

更新后的 json 文件显示如下。id 为 2 的帖子曾经有类似帖子的内容。

...
"posts": [
    {
      "id": 2
    },
    {
      "id": 3,
      "title": "Post Three",
      "body": "This is post three."
    },
...

标签: javascriptjsonwebpackcrud

解决方案


感谢@DDupont,我能够找到我出错的地方。HTTP PUT 请求的标头中非常简单的粗心拼写错误。

"Content-type": "application.json"

我在那里有过一段时间。这应该是...

"Content-type": "application/json"

推荐阅读