I have an assignment about using Javascript API. I don’t know anything about Javascript APIs. Can anyone help me? I wrote the login page with html css code. But the second stage of the assignment:
- When the login button on the login page is clicked, the values ​​entered in the username and password inputs will be received with Javascript and a request will be sent to the service here https://fakestoreapi.com/docs#a-login. When a response comes from this service, a redirection will be made to the dashboard page from the login page.
I’m very new to the software, I searched for a video to learn, but I couldn’t find it for the login page. Can anyone help me.
I was able to create a login page using only html css.
>Solution :
This is how I would implement it
myform.addEventListener("submit", function(evt) {
evt.preventDefault();
let fields = this.querySelectorAll("[name]");
let obj = {};
for (let field of fields) {
obj[field.name] = field.value;
}
fetch('https://fakestoreapi.com/auth/login',{
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body:JSON.stringify(obj)
})
.then(res=>res.json())
.then(json=>console.log(json))
});
<form id="myform">
<input type="text" placeholder="username" name="username" value="mor_2314">
<input type="password" placeholder="password" name="password" value="83r5^_">
<input type="submit" value="login">
</form>
I created a form and a submit event for it. I preventDefault in the submit event so we don’t do a postback. We also specify that our values are JSON and convert our collected values into JSON.