Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form submit vs. Javascript POST Request

I'm making a POST request with a very simple HTML form. The request fails in the form format, but works in Javascript.

It's very simple, so here is almost the entire form:

<form method="post" action="[apiUrl]" target="_blank">
  <input type="hidden" name="payload" value="[payload]">
  <!-- ... -->
</form>

*Please note that [apiUrl] and [payload] are variables that are injected into the HTML.

The request fails with a custom message from the API (seems it can't parse the payload):

{
  "Error": {
    "Message": "Noun and Verb are Required Request Parameters",
    "ValidationError": false
  },
  "Result": "ERROR"
}

However, the exact same request will succeed when performed by Javascript (I've tested with both Axios and jQuery, and also with Paw).

$.post(this.apiUrl, this.payload, response => {
  console.log('Success!', response);
});

The payload is just a Javascript Object. The variables are set like this:

this.apiUrl = request.url;
this.payload = JSON.stringify(request.parameters);

Why does it fail as a form?

like image 300
Donnie Avatar asked Dec 08 '25 08:12

Donnie


1 Answers

I met similar problem when I was building the back-end(using Node&Express.js) and front-end(Angular.js) separately using JSON apis. And it took 12 hours to find the reason why not working with html forms.
The problem was on the back-end side, when you submit using jquery $.post, Content-type is application/json but when you submit using html form Content-type is application/form-data.

You can test the APIs using postman, if you select the content-type as form-data that api will not work.

So to solve the problem, you have to rebuild backend apis to be compatable with Content-type application/form-data.

Additionally in my case, I used body-parser node package to analyze form data.

like image 96
artgb Avatar answered Dec 09 '25 22:12

artgb