Express usage - adam-kostuch/terminal-backend GitHub Wiki

In order to write some code in backend you need to get to know what's written better! Let's start with the src/index.ts file. First of all there are import. As you can see below importing express looks like this:

import * as express from "express"

and not like this:

import express from "express"

why like that? Because Typescript requires it, that's all. Other worth mentioning thing is connecting MongoDB, as you can see there is a function connectDB taken from the db/config.ts file which uses mongoose connect method. Then you simple use it like it's shown in the 7th line.

HINT: Try to use async functions everywhere!
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(async (_req: Request, res: Response, next: NextFunction): Promise<void> => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET")
  next()
})

Two first lines in this code allows the usage of JSON through the application. The rest is meant to set headers, to allow all the methods shown above.

app.use("/user", UserRouter)
app.use("/flight", FlightRouter)

app.get("/", async (_req: Request, res: Response): Promise<Response> => {
  return res.status(200).send("Hello World")
})
HINT: You can try all the endpoints in the src/request.rest file. The only thing you need to run it is the extension REST Client in your vscode. 

This one right here is managing all of our enpoints in this app! So we're setting the router (all of the endpoints gatherated in one this) and connecting it to /user or /flight endpoint. Also the last get method gets our default page request.

try {
  app.listen(port, (): void => console.log(`Connected successfully on port ${port}`))
} catch (error) {
  console.error(`Error occured: ${error.message}`)
}

The code shown above is probably the most important one. It runs our appplication on port (declared above in code) and logging the message if it works or not.

The rest of the code is shown in the src/ folders so go ahead and check them.

⚠️ **GitHub.com Fallback** ⚠️