【问题标题】:Issue with Sequelize Query and PUT errors in ChromeChrome 中的 Sequelize Query 和 PUT 错误问题
【发布时间】:2018-01-10 12:51:48
【问题描述】:

学生问题!

我正在学习使用 Sequelize ORM 的 Node.js/Express 和 MySQL 数据库。传统上,在我们的简单应用程序中,使用 Sequelize 查询 MySQL 数据库后,我们将在 Express PUT 路由的 .then 承诺中发出res.redirect('/'),类似于:

app.post("/", function (req, res) {
    db.Burgers.create({
      burger_name: req.body.burger_name
    }).then(function () {
      res.redirect('/');
    });
  });

我在使用findOrCreate() 方法创建续集查询时遇到了问题。也就是说,我正在努力寻找将 res.redirect 语句放在 AJAX PUT 请求上的位置。出于某种原因,当我在 PUT 语句的快速路由中附加了 res.redirect('/') 时,我会在 Chrome 网络检查器中看到重复的 PUT 请求。第一个 PUT 请求显示为 (localhost:3000/devour, type:text/plain, status:302)。

Express 服务器接收到 PUT 请求并且 sequelize 查询成功,更新 MySQL 数据库中的正确表。但是,Express 路由上的重定向没有成功,Chrome Inpector 显示错误“PUT http://localhost:3000/ 404 (Not Found)”,当我查看“网络”选项卡时,我看到了第二个 PUT 请求(localhost:3000/,输入: xhr,状态:404)。

这是 Express PUT 路由:

app.put("/devour", function (req, res) {
var customerId;
// Check to see if the customer name entered already exists, if not create
db.Customers.findOrCreate({
  where: {
    customer_name: req.body.customer_name
  }
})
.spread((user, created) => {
  if (created) console.log("User created");
  customerId = user.id;
  var update = {
    "devoured": req.body.devoured,
    "CustomerId": customerId
  };
  db.Burgers.update(update, {
    where: {
      id: req.body.id
    }
  }).then(function () {
  res.redirect('/');    
});
})
});

生成第二个 PUT 请求的原因是什么?是响应而不是请求?

这是我第一次使用 findOrCreate() 方法进行 Sequelize 查询,所以我可能误解了 .spread() 的使用。

如果我在 PUT Express 路由上注释掉 res.redirect,则不会发生错误,但我必须手动刷新页面才能查看 MySQL 数据库中的更新数据。

======================================
我在我的 Express PUT 路由中添加了 303 状态代码:res.redirect(303, '/')。这消除了重定向上的 404 错误,但是 HTML 页面没有通过 GET 请求刷新以使用 PUT 请求的更新重新加载页面。

然后我查看了我的 Ajax 调用并意识到,也许我需要在那里添加代码来处理来自服务器的响应:

$.ajax({
    url: URL,
    type: 'PUT',
    contentType: 'application/json',
    data: JSON.stringify(dataObject)
  })

所以我添加了一个 .done 承诺回调,页面在 PUT 请求之后成功刷新:

$.ajax({
    url: URL,
    type: 'PUT',
    contentType: 'application/json',
    data: JSON.stringify(dataObject)
  }).done(function(){
    window.location.href = window.location.origin + '/'
})

我想我有点困惑,为什么单独使用服务器端 res.redirect(303, '/') 不会导致客户端的页面刷新。提供“/”路径作为参数有什么意义?

谢谢!

【问题讨论】:

    标签: node.js ajax express sequelize.js


    【解决方案1】:

    您可以在Why POST redirects to GET and PUT redirects to PUT? 中阅读更多关于重定向标头包含在 PUT 请求中时的作用

    长话短说,您的 PUT 请求仍然是 PUT 请求,只是被重定向到 /

    如果您提供 303 状态代码,您的应用应该可以正常运行。

    res.redirect( 303, '/' );
    

    【讨论】:

    • 感谢您提供此信息!将 303 状态代码添加到重定向确实可以消除重定向请求上的 404 错误,但是它不会在“/”(localhost:3000/)处重新加载页面,这会触发 GET 请求将数据库更改更新到屏幕上。
    • 我不知道你有 Ajax 调用。重定向仅适用于 Ajax 响应,因此基本上没用。像你一样将它添加到 promise 回调中,是正确的方法!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 2019-07-17
    相关资源
    最近更新 更多