Reputation: 306
I am very new to HTML and JavaScript. I have created a very simple HTML page for log-in functionality. The code is as below.
<html>
<head>
<body>
<form>
<p>Username</p>
<input type='text' name="" placeholder="Enter Username/Email ID">
<p> Password</p>
<input type='password' name="" placeholder="Enter Password">
<input type='submit' name="" value="LogIn the User">
</form>
</body>
</head>
</html>
Now I have a RESTful API having login functionality. I can send the values of Username and Password for API testing in POSTMAN in the json format.
Now my question is how can I connect the rest of API of login with my HTML page. If it is a duplicate question then please bring me to the original one. Also, if you can suggest some resources. I have gone through a lot but could not find the relevant. Thanks.
Upvotes: 0
Views: 88
Reputation: 64695
The basic steps would be to
document.forms[0].addEventListener('submit', function(e) { // when they submit
e.preventDefault(); // Don't try and submit the form the traditional way
const data = {
username: e.target.querySelector('input[name="username"]').value,
password: e.target.querySelector('input[name="password"]').value
} // get the JSON we want to submit
fetch('/auth/login', {
method: 'post', // submit it as a post request
body: JSON.stringify(data)
}).then(function(response) {
return response.json(); // parse the response as json
}).then(function(data) {
console.log('do something with the response');
});
});
<html>
<head>
<body>
<form>
<p>Username</p>
<input type='text' name="username" placeholder="Enter Username/Email ID">
<p> Password</p>
<input type='password' name="password" placeholder="Enter Password">
<input type='submit' value="LogIn the User">
</form>
</body>
</head>
</html>
Upvotes: 1