【问题标题】:How to make a Post, Put or Delete followed by a get fetch?如何在获取获取后进行发布、放置或删除?
【发布时间】:2019-07-20 09:23:36
【问题描述】:

我有一个用 ExpressJS 编写的 API。现在我正在使用 websocket 服务器从该 API 获取数据,但是当我执行一些更新(POST、PUT 或 DELETE)数据库(Postgres)然后是 GET 申请时,我遇到了问题。

我期待 GET 获取返回所有记录的列表,包括我刚刚更新的记录,但不包括新记录。

然后我在我的更新操作和新的 GET 之间添加了一个超时。我知道这不是一个好的解决方案,因为当许多用户同时发送请求时,我定义的超时可能无法正常工作。

client.on('deleteData', (id) => { 

fetch(server+id, {
method: 'DELETE',
})
.then (
setTimeout(function(){ 
fetch(server)
.then(response => response.json())
.then(//params separated with ,
responseJson => { 
client.emit('getData', responseJson.data)
client.broadcast.emit('getData', responseJson.data) /
console.log(responseJson.data)
console.log("eliminated!")
}) }, 1000))
.catch((error) =>{
console.error(error)
client.emit('getData', error)
})})

如果我从我的代码中取出超时,新的更新(在本例中为 DELETE)不会反映在我在下一次 GET 中获得的数据集中。

有人能帮我找到一种方法来等待更新数据可用于下一次 GET 的确切时间吗?

【问题讨论】:

    标签: rest api express websocket socket.io


    【解决方案1】:

    我找到了解决方案,GET 申请应该在 POST 回调中:

    client.on('eliminarCliente', (id) => { 
      fetch(server+id, {
      method: 'DELETE',
      })
      .then (response => response.json())
      .then (responseJson => {
        fetch(server)
        .then(response => response.json())
        .then(responseJson => { 
          client.emit('getData', responseJson.data)  
          client.broadcast.emit('getData', responseJson.data)
        })
        .catch((error) =>{
        client.emit('getData', error)
        })  
      })
     .catch((error) =>{
        client.emit('getData', error)
     })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 2014-10-20
      相关资源
      最近更新 更多