0

I try to fetch login datas in a Svelte/Sapper app as in the code below and I use polka and axios for the api request on the server.

I don't understand the behaviour in the axios call. The console.log(JSON.stringify(result.data)) logs the correct result as I expected. But the fetch request on the client throws this exception:

Error: Failed to fetch

Can anyone explain me what I do wrong?

//client
try {
      const res = await fetch("login.json", {
        method: "POST",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({ user: email, passw: password }),
      });
      let result = await res.json();
     
      if (!res) {
        throw new Error(result.error);
      }else{
        console.log("result: "+JSON.stringify(result));
      }
    } catch (e) {
      error = e.message;
      console.log("Error: "+error); //Error: Failed to fetch
    }
  }
//server
export async function post(req, res) {
    const password = sha3_512(req.body.password);
    const qs = require('qs');
    const data = qs.stringify({ user: req.body.user, password: password })
    const config = {
        method: 'post',
        url: 'https://****login',
        httpsAgent: agent,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: data
    }
    
    axios(config)
    .then(result => {
        console.log(JSON.stringify(result.data));//successful response
        res.end(JSON.stringify(result.data));
    })
    .catch(err => res.end(err));
}
Paolo
  • 20,112
  • 21
  • 72
  • 113
Jaqen
  • 23
  • 4
  • I have just seen that if I open the Chrome DevTools, the fetch request works. But as soon as I close the DevTools it does not work anymore and it throws the "Failed to fetch" Error. That looks very strange for me. Is it an issue about anything with CORS maybe? – Jaqen May 27 '21 at 07:04

1 Answers1

0

The problem is solved after add preventDefault in the form element.

 <form on:submit|preventDefault={() => submit()}>
Jaqen
  • 23
  • 4