从HTML中删除对Nancy的请求

本文关键字:Nancy 请求 删除 HTML | 更新日期: 2023-09-27 18:06:41

我在Nancy中实现了一个REST API。我对以下端点使用DELETE:

Delete ["/usermanagement/{id}"] = parameters => {
            repo.DeleteUser(parameters.id);
            return Response.AsRedirect("/usermanagement");
        };

我想从我的简单html页面调用这个结束点。到目前为止,我想出了这个解决方案:

<button type="button" onclick="deleteUserWithID('@Current.ID')">Delete</button></td>

和JS:

<script>
    function deleteUserWithID( ID ){
      var xhr = new XMLHttpRequest();
      xhr.open( 'DELETE', 'usermanagement/' + ID, false );
      xhr.setRequestHeader( 'Content-Type', 'text/html' );
      xhr.send(null);
    }
</script>

这是有效的,只要到达端点,执行业务逻辑。问题是,这不会回到AsRedirect("/usermanagement"); ie。:它不会重新加载页面。我试过直接从POSTMAN执行这个端点,没有上面的任何JS,我得到了预期的html (/usermanagement)页面。

有人遇到过类似的问题吗?什么可能是错误的,上面的JS,它导致南希不返回/usermanagement页时,从浏览器执行(通过邮差执行时返回此页)?

从HTML中删除对Nancy的请求

浏览器重定向不像AJAX (Ie, XMLHttpRequest)那样工作。如果您检查xhr.responseText属性,我认为您会发现它包含/usermanagement页面的HTML。但是,如果你想把浏览器重定向到那个页面,你应该通过JavaScript:

function deleteUserWithID( ID ){
  var xhr = new XMLHttpRequest();
  xhr.open( 'DELETE', 'usermanagement/' + ID, true );
  xhr.setRequestHeader( 'Content-Type', 'text/html' );
  xhr.onreadystatechange = handleResponse;
  xhr.send(null);
}
function handleResponse(e) {
  if (this.readyState == 4) {
    if (this.status == 200) {
      location.href = "/usermanagement";
    }
  }
}