Basic HTTP authentication
08.07.2020
In the previous section, I created a simple registration form that takes user input and validates for client-side errors.
What to do next?
- We need to send a HTTP request to the server to register a user in the database
- Server receives the data, and checks for any server side errors.
- Server tells us whether the request is accepted or rejected.
- Based on the server response, we need to redirect the user to the appropriate page.
1. Sending an HTTP request to the server
In this example, I'm going to use axios. Install axios
npm i axios
Import axios in the Registration.js
import axios from "axios"
Call the server onSubmit
const handleSubmit = event => {
event.preventDefault()
const errors = validate()
setErrors(errors || {})
if (errors) return
//call server
postData()
}
In the handleSubmit
method, we need to call the server right after client-side validation passes. We will place the call separately inside the postData
method.
In the postData
method, first call the server
const postData = () => {
axios.post("http://localhost:3900/api/users")
}
In order to ask the server to accept data, need to send a POST request. Here, I'm sending the request to the backend server that I set up with the node.js and mogodb.
But what are we asking the server to accept? The user input.
const postData = () => {
const userData = {
name: account.name,
email: account.username,
password: account.password,
}
axios.post("http://localhost:3900/api/users", userData)
}
Include user input in the body of the request. The keys should match with the backend.
The request will return a promise. What's a promise?
const postData = async () => {
const obj = {
name: account.name,
email: account.username,
password: account.password,
}
const response = await axios.post("http://localhost:3900/api/users", obj)
}
We need to await
for the promise, and place the response in a const. Lastly, decorate the function with an async keyword.
Now test registering a user
Once Register button clicked, check the Network tab in the Chrome developer tool
Under users, Status code shows 200 OK. Successfully saved the user data in the server.It successfully shows up in the MongoDB as well
To be continued...