Epitouille Epitouille - 4 months ago 20
Javascript Question

Using the javascript fetch api to perform a POST request

I would like to reproduce the behavior of this cURL request :

➜ % curl --data "" https://api.t411.ch/auth
{"error":"User not found","code":101}


In this case, the server send me back JSON.

The code I use in Javascript is :

fetch('https://api.t411.ch/auth/', {
method: 'POST'
}).then(response => {
return response.json();
}).then(datas => {
console.log(datas);
});


With that, I get a parsing json error, so, I decided to return
response.text()
instead of
response.json()


The
console.log(datas)
prints :
string(5) "1.2.4" Service 'view' wasn't found in the dependency injection container


It's the same string that I get when I access to the url : https://api.t411.ch/auth with my browser (GET request).

That means that my javascript code send a GET request, even with the
method: 'post'


What am I doing bad ?

PS: I think it's not related at all, but I use es6/jsx transpiled by babel in an electron project.

Thanks

Answer

Your code is trying to POST to https://api.t411.ch/auth/. It should be https://api.t411.ch/auth instead. This should work fine:

fetch('https://api.t411.ch/auth', {
    method: 'POST'
}).then(response => {
  return response.json();
}).then(datas => {
  console.log(datas);
});