【问题标题】:Is there any way to create a POST HTTP request using window.location?有没有办法使用 window.location 创建一个 POST HTTP 请求?
【发布时间】:2021-11-17 02:53:45
【问题描述】:

我有一个使用 node 和 express 构建的 web 应用程序,我想在 ejs 文件中提交一个表单,但我不能使用form.submit(),因为我想在 URL 中传递参数。

表单的id是"update",提交按钮的id是"btnsubmit",我目前正在尝试发送post请求如下:


var form = document.getElementById("update");
document.getElementById("btnsubmit").addEventListener("click", function () {
  var lp = "1";
  window.location = ("/dbinsertupdateditem?loadpage="+encodeURIComponent(lp));
});

单击按钮时出现错误:Cannot GET /dbinsertupdateditem,因为快速路由需要 POST 请求。是否可以使用 window.location 发出 POST 请求,还是我需要采取不同的方法来解决这个问题?

【问题讨论】:

  • 不,window.location.href 是一个 GET。您需要发布表格。

标签: javascript node.js express http ejs


【解决方案1】:

您无法更改 window.location.href 的工作方式。因此,如果路由器希望它是一个帖子,您需要发布一个表单。如果页面上有表单,则可以设置操作

var form = document.getElementById("update");
form.action = "/dbinsertupdateditem?loadpage="+encodeURIComponent(lp);
form.submit();

如果您没有表单,请创建一个

var form = document.createElement("form");
form.method = "POST";
form.action = "/dbinsertupdateditem?loadpage="+encodeURIComponent(lp);
document.body.append(form);
form.submit();

或者可能是最好的答案,更改您的后端以允许 GET

【讨论】:

  • 太棒了,谢谢。如果我将后端更改为允许 GET,我是否仍然能够访问发出 HTTP POST 请求时发送的request.body??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多