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));
}
The problem is solved after add preventDefault in the form element.
<form on:submit|preventDefault={() => submit()}>