【问题标题】:XMLHttpRequest is throwing an error for non-200 statuses [duplicate]XMLHttpRequest 为非 200 状态引发错误 [重复]
【发布时间】:2018-08-19 02:03:10
【问题描述】:

为了验证我网站上的登录,我向服务器发送了一个 POST 请求。如果返回403 状态,则表示凭据不正确,200 状态表示登录成功。

这是我用来发送请求的代码:

var req = new XMLHttpRequest()
var form = document.getElementById("login")

req.onreadystatechange = function() {
    if (req.readyState !== 4) return

    if (req.status === 200) {
        console.log(req)
    } else if (req.status === 403) {
        document.getElementById("login-err").innerHTML = req.responseText
    } else {
        document.getElementById("login-err").innerHTML = "internal server error"
    }
}

req.open("POST", `https://${window.location.host}/newsession`, true)
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
req.send(`username=${form.username.value}&password=${form.password.value}`)

它适用于200 状态,但当状态为403(或500)时,控制台会记录错误:Failed to load resource: the server responded with a status of 403 (Forbidden)

虽然这不是一个 巨大 问题,但我希望,由于我正在处理状态代码,因此不应该出现错误。有没有办法解决这个问题?

【问题讨论】:

    标签: http post xmlhttprequest


    【解决方案1】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多