Home > Net >  Is there any way to create a POST HTTP request using window.location?
Is there any way to create a POST HTTP request using window.location?

Time:11-17

I have a web app built using node and express, and there is a form I want to submit in an ejs file, but I cannot use form.submit() because I want to pass parameters in the URL.

The form's id is "update" and the submit buttons id is "btnsubmit", I am currently trying to send the post request as follows:


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

On button click I get the error: Cannot GET /dbinsertupdateditem, because the express route is expecting a POST request. Is it possible to make a POST request with window.location or do I need to go about a different way of solving this?

CodePudding user response:

You can not change how window.location.href works. As a result, you need post a form if the router expects it to be a post. If you have a form on the page you can just set the action

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

If you do not have a form, create one

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

Or probably the best answer, change your backend to allow GET

  • Related