layout | title |
---|---|
../../layouts/CheatSheet.astro |
ExpressJs Cheatsheet |
Express.js is a web application framework for Node.js. It is designed for building web applications and APIs. It has been called the de facto standard server framework for Node.js.
You need to have node.js installed
Run the below command to quickly create an application skeleton
npx express-generator
And then run
npm i
to install all necessary modules
add this code in app.js
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
and run app.js to start the serve. Go to localhost:port to see the response
The routing definition syntax is
app.METHOD(PATH, HANDLER)
Here, METHOD is an HTTP request method, and HANDLER is the function executed when the route is matched.
app.get('/', (req, res) => {
res.sendFile(__dirname +'/views/index.html') ;
})
Static assets include things like css files app.use('/public',express.static(__dirname + '/public'));
Serve a JSON response app.get('/json',myFunction2); function myFunction2(req, res) { res.json({"message": "Hello json"}) ; }