Post Functions
There are different status codes that range from 100-500. The key status codes that are used often are the ones found inside the range of 200s, 400s, and 500s.
The 200s shows success such as when a request has succeeded, a new resource was created, or when an change to some data has successfully occurred. The 400s shows client errors which include bad requests (when fields are missing or the syntax is bad), unauthorized requests where you are not authenticated, or when you don’t have permission to access something. The 500s shows server errors which mainly occur when there are underlying issues within the backend.
Destructuring makes accessing data inside an object easier.
const { username, name, password } = req.body;
console.log(username)
console.log(name)
console.log(password)
/*
This is a quicker and more efficient way to
access information from the body object
which is located inside of the req object.
*/
A post function checks to see whether the data entered by a user matches all the fields required by the program and depending on the request, the function sends the success statement and a message from the backend to the frontend.
app.post('/sign-in',(req,res)=>{
try {
const {username, password} = req.body
if(!username || !password){
return res
.status(400)
.json({
success:false,
message:"Please send username and password"
})
}
const user = user.find(
(user)=> user.username === username && user.password === password
)
if(!user){
return res
.status(401)
.json({
success:false,
message:"Invalid credentials"
})
}
return res
.status(200)
.json({
success:true,
message:"User signed in successfully",
data:user
})
} catch (error) {
return res
.status(500)
.json({
success:false,
message:"Internal Server Error",
error:error.message
})
}
})
//This is an example of a post function with exception handling