fetch 可以代替 AJAX 吗?

Can fetch be a substitute for AJAX?

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

我知道您可以在 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)

你太接近了!你已经获取了数据,然后用 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() 抛出的错误。所以你需要为错误添加一个参数,以及一个函数体来处理它。我编辑了我的代码示例以进行演示。

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