I made a decorator on Flask, which should accept a JSON string from the html form.

@app.route('/processjson', methods=['POST']) data = request.get_json(force=True) return jsonify(data) 

Through Postman I checked the POST request by sending a JSON string. Everything is working. However, sending the form itself from the client, I get:

400 Bad Request: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

It turns out that the form generates the wrong format.

Here is the form:

 <form action="/processjson" enctype="application/json" method="post"> <input type="hidden" name="name" value="Bender"> <input type="submit" value="TEST"> </form> 

request.headers['Content-Type'] returns 'application/x-www-form-urlencoded'

The task is that I have to get a JSON string from a form, and after some operations, send a JSON string to the same form.

  • one
    Browser forms do not support json - andreymal
  • darobin.imtqy.com/formic/specs/json and what about this say? - Sturm Tiger
  • one
    I will say that the presence of some DRAFT handwriting on the Internet does not negate the fact that in 2018 the browser forms do not support json (although the handwriting is good, yes) - andreymal
  • one
    First, the “client side” is not necessarily a browser (unless explicitly stated in the task). Secondly, in browsers you can use javascript, without using forms, to send completely arbitrary data, including json - andreymal
  • one
    The term “one-page web application” almost certainly implies the term SPA, which almost always means writing almost everything on JS (traditionally using some React, Vue or Angular), in which you can, among other things, send AJAX requests to the server with json data (using XMLHttpRequest or fetch, the second is preferable). Here, the keywords for Google, I gave you :) - andmalmal

1 answer 1

Browser forms do not support application/json . And, it seems, they will never support:

Caution! This specification is not supported, and the HTML Working Group does not want to support it in the future.

You can send requests with application/json javascript. In the simplest key / value cases, you can simply walk through FormData and collect all the keys into an object, which you then encode in json and send:

 document.getElementById('benderform').addEventListener('submit', submitForm); function submitForm(event) { // Отменяем стандартное поведение браузера с отправкой формы event.preventDefault(); // event.target — это HTML-элемент form let formData = new FormData(event.target); // Собираем данные формы в объект let obj = {}; formData.forEach((value, key) => obj[key] = value); // Собираем запрос к серверу let request = new Request(event.target.action, { method: 'POST', body: JSON.stringify(obj), headers: { 'Content-Type': 'application/json', }, }); // Отправляем (асинхронно!) fetch(request).then( function(response) { // Запрос успешно выполнен console.log(response); // return response.json() и так далее см. документацию }, function(error) { // Запрос не получилось отправить console.error(error); } ); // Код после fetch выполнится ПЕРЕД получением ответа // на запрос, потому что запрос выполняется асинхронно, // отдельно от основного кода console.log('Запрос отправляется'); } 
 <form action="/processjson" id="benderform"> <input type="hidden" name="name" value="Bender"> <input type="submit" value="TEST"> </form> 

(Of course, in reality everything should not look so clumsy as in this example (and in general this example does not work, because Stack Overflow snippets do not provide for testing ajax requests), but I gave direction for further actions.)

Documentation: FormData , Fetch , async / await , XMLHttpRequest (if you need support for older browsers)