【问题标题】:Can fetch be a substitute for AJAX?fetch可以代替AJAX吗?
【发布时间】:2019-06-03 17:46:46
【问题描述】:

我想知道是否可以在获取传统 ajax 中可以做的所有事情? 因为我在使用 express 进行简单的登录身份验证时遇到问题。如果用户名/密码不正确,我想向客户端发送类似登录错误的响应,或者如果两者都正确,则将用户重定向到主页,而不刷新页面。

我知道您可以在 AJAX 中执行此操作,但是否也可以在 fetch 中执行此操作?

我尝试使用 express js 并通过 json 发送响应,但我无法弄清楚如何在不刷新页面的情况下处理响应。

我尝试在快递服务器上这样做

//if valid
res.json({
    isValid: true
})

//if invalid
res.json({
    isValid: false
})

在客户端,特别是在登录页面,我有这个处理信息提交的javascript

fetch('https://localhost:3000/auth', {
    method: 'post',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        username,
        password
    })
})
.then(response => response.json())
.then(data => {
     //I understand that in this part, you can handle the response, but the problem is, I don't know how.
    }
})
.catch(console.log)

【问题讨论】:

  • fetch 执行 ajax 请求。 ajax 是一种从服务器端异步获取数据的技术的通用名称。
  • 但是是的,fetch 是对我们十年前的 ajax 混乱的一个很好的更新,只要您使用的浏览器支持它。
  • 对不起,我的意思是如果你可以在 fetch 中做所有你可以用传统 ajax 做的事情。将更新问题。
  • @Ardi 没有“传统的 ajax”,ajax - 是一种技术的名称,而不是特定的产品/实现。你可能是说 xhr。

标签: ajax express fetch-api


【解决方案1】:

你离得太近了!你得到了 fetch,然后你用 response.json 解析了它,所以接下来就是 .then()。在那里,您将 JSON 对象传递到您命名为 data 的参数中。您需要做的就是检查它是否具有isValid 属性!

fetch('https://localhost:3000/auth', {
    method: 'post',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
        username,
        password
    })
})
.then(response => response.json())
.then(data => {
     if(data.isValid){
       // Do something with a valid user. Redirect or whatever.
     } else {
       // Here, isValid is not set, or is false.
       //  Send them packing!
     }
    }
})
.catch(err => console.error("I died: ", err) );

另外,查看.catch() 块——如果发生错误,它会捕获fetch()then() 抛出的错误。所以你需要为错误添加一个参数,以及一个函数体来处理它。我已经编辑了我的代码示例以进行演示。

实际上不会在这里运行,但它的格式很漂亮。

【讨论】:

  • 谢谢!正是我需要的。但是最后一个问题,你能在 fetch 中做所有你可以用传统 ajax 做的事情吗?
  • @Ardi xhr 可以同步,fetch 不能。
  • 我在任何可能使用过 $.ajax() 的地方都使用 fetch,是的。
猜你喜欢
  • 2019-02-07
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 2015-01-30
相关资源
最近更新 更多