Why does the page reload after sending a POST request to the json-server-auth (local database)? How to solve this problem? Due to the reboot, I don't have time to get the data and record it.
<form >
<input type="email">
<input type="password">
<button>Регистрация</button>
</form>
<code lang="javascript">
const form = document.querySelector('.form')
form.addEventListener('submit', async (e) => {
e.preventDefault()
let data = {
email: e.target[0].value,
password: e.target[1].value
}
let res = await fetch('http://localhost:8080/signup', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
let json = await res.json()
console.log(json)
return false
})
I tried the same code in codepen and there is no reboot, but when sending from the browser via Live Server in VS Code, the page is reloaded.
CodePudding user response:
As @Nico already mentioned: if you replace your "code"-tag with <script>
it will work:
<body>
<form >
<input type="email">
<input type="password">
<button>Регистрация</button>
</form>
</body>
<script>
const form = document.querySelector('.form')
form.addEventListener('submit', async (e) => {
e.preventDefault()
let data = {
email: e.target[0].value,
password: e.target[1].value
}
// I replaced your sign-up-URL with a publicly available API for testing:
let res = await fetch('https://jsonplaceholder.typicode.com/users', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
let json = await res.json()
console.log(json)
})
</script>
CodePudding user response:
I found reason. It was Live Server VS Code. When i send request in my local bd.json, live server reload my page. I added db.json in ignor, and now it work)