-2

I have a problem with setting JSON data in a GET request. I tried: As POST request (with POST request it works)

xhr.open("GET", "http://localhost/test", true);
body = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
xhr.send(body);

As query string:

var json = {"hello": "world"};
var url = "http://localhost/test?data=" + encodeURIComponent(JSON.stringify(json));
xhr.open("GET", url, true);
xhr.send();

On the backend method, req.json returns null, but I can see the query string.

Also, it works in Postman if I set JSON data to the body. On the backend, I see JSON data in the request.

P.S.: In my previous project I used the same backend framework but the frontend was based on jQuery instead of pure JS and the ajax method worked correctly.

Wusiki Jeronii
  • 159
  • 1
  • 8
  • Wouldn’t it be `req.params.data` on the backend? – evolutionxbox Nov 28 '21 at 10:56
  • @evolutionxbox, no. `req.params` - is a data from forms – Wusiki Jeronii Nov 28 '21 at 10:57
  • @evolutionxbox, checked it out now. I set 3 lines: `req.json`, `req.queryString`, `req.params`. Output: `null`, `data=%7B%22Hello%22%3A%5B1%2C2%2C3%5D%7D`, `[]` – Wusiki Jeronii Nov 28 '21 at 11:01
  • What about `req.query.data`? – evolutionxbox Nov 28 '21 at 11:25
  • Does this answer your question? [How to get GET (query string) variables in Express.js on Node.js?](https://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js) – evolutionxbox Nov 28 '21 at 11:26
  • @evolutionxbox, no. I know how to get queryString. Look above (data...... is a queryString) But it is a string. As it works in Postman adding JSON to the body I think I need to also add JSON to the body in JS. But how? Looks like in "GET" requests XMLHttpRequest empties body. – Wusiki Jeronii Nov 28 '21 at 11:37
  • Get requests do not have a body. Once you have the json string in the back end, use `JSON.parse` to convert the JSON into a js object – evolutionxbox Nov 28 '21 at 11:40

1 Answers1

-2

2 months without web development born such stupid questions. I don't use node.js but I think node.js acts so. I remembered the right way. I have tried to use "localhost?data={a: 9}" but the correct way is "localhost?a=9". The backend will parse all query variables as input in the Rest interface. Thanks to @evolutionxbox for kicking to the right side.

Wusiki Jeronii
  • 159
  • 1
  • 8