【问题标题】:How to properly update in a CRUD application如何在 CRUD 应用程序中正确更新
【发布时间】:2019-06-14 21:16:14
【问题描述】:

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

Post 1

content for post 1

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

Undefined

Undefined

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

在我的 http.js 文件中,put 请求与所有其他请求(发布、放置、删除、获取)一起位于 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."
    },
...

【问题讨论】:

  • 你能解释一下你的“没有来自 webpack 的警告”评论的意思吗?
  • 这是一个错误。我习惯于在 React 和 Django 等框架中构建,在这些框架中我会收到此类错误的通知,并且可以将这些事情追溯到问题的根源。在构建这个应用程序时,我希望摆脱对它们的依赖。一段时间以来,CRUD 的更新部分一直是我的一个特别弱点,我希望至少有人能给我建议,告诉我如何跟踪问题或告诉我哪里出错了。你有什么建议吗?
  • 您是否通过浏览器的网络跟踪工具查看了 ajax 调用以准确了解 PUT 与 POST 或 GET 中的内容?最好将其隔离到 PUT 以确保
  • 按照你的建议我做了。我也在邮递员上试过。邮递员一切都很好,但从我在跟踪工具上看到的情况来看,put 请求有问题。我们正在缩小范围。

标签: javascript json webpack crud


【解决方案1】:

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

"Content-type": "application.json"

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

"Content-type": "application/json"

【讨论】:

  • 一直就在我们的眼皮底下 :) 人们想知道为什么软件要花这么多时间!
猜你喜欢
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多