// const express = require('express')
// import express
importexpressfrom'express'// call express to start server
constapp=express()constport=3000// .get takes route and fx for what to do
// args are req object and res object
app.get('/',(req,res)=>{// Send something back to user
res.send('Hello World!')})// Set the server to listen on a prescribed port
app.listen(port,()=>{console.log(`Example app listening on port ${port}`)})
This app starts a server and listens on port 3000 for connections and responds with “Hello World!” for requests to the root URL (/) or route. For every other path, it will respond with a 404 Not Found.
nodemon can be used to restart the server on changes.
send() can send text, HTML, or JSON object or array.
app.get(``,(req,res)=>{// first arg is view to render
// second arg is dynamic values to pass
res.render(`index`,{title:`Weather App`,name:`Andrew Mead`,})})
Express doesn’t provide a way to force requiring a query, instead we can use simple if statement.
1
2
3
4
5
6
7
8
9
10
app.get(`/products`,(req,res)=>{if(!req.query.search){returnres.send({error:`You must provide a search term`,})}res.send({products:[],})})
We can also send back query data normally in response.
1
2
3
4
5
6
7
8
9
10
11
app.get(`/weather`,(req,res)=>{if(!req.query.address){returnres.send({error:`You must provide a location.`,})}res.send({forecast:`The weather forecast is that there will be weather whether or not you can weather it.`,location:req.query.address,})})