This is the 26th day of my participation in the August More Text Challenge
Express route
Routing path
The routing path, in combination with the request method, defines the endpoint to which the request can be made. The routing path can be a string, string pattern, or regular expression. Characters? , +, *, and () are corresponding subsets of their regular expressions. The hyphen (-) and dot (.) Interpreted literally by string-based paths. If you need to use the dollar character () in the path string, escape it ([enclosed in and]). For example, ‘/data/ uses the dollar character () in the path string, escape it ([enclosed in and]). For example, ‘/data/ uses the dollar character () in the path string, escape it ([enclosed in and]). For example, the requested path string at ‘/data/book’ would be “/data/([$book])”.
Express uses path-to-regexp to match routing paths. For all the possibilities of defining routing paths, see the regular expression paths documentation. Express Route Tester, while not supporting pattern matching, is a handy tool for testing basic Express routes. The query string is not part of the routing path.
The path parameter
Route parameters are named URL segments because they capture the value specified at the starting point in the URL. The captured values are populated into the req.params object with the names of the route parameters specified in the route as their respective keys.
Start a small project
const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const router = require('./router')
const app = express()
// Set the port number
const PORT = process.env.PORT || 3000
// Parse json data
app.use(express.json())
// Prints logs
app.use(morgan('dev'))
// Provide cross-domain resource requests to clients
app.use(cors())
app.use('/api',router)
app.get('/'.(req,res) = >{
res.send('Hello Word')
})
app.listen(PORT,() = >{
console.log('Started successfully')})Copy the code
Create several files under the Router folder to place all related routes in the same file
const express = require('express')
const router = express.Router()
// User-specific routes
router.use(require('./user'))
// article related route
router.use(require('./profile'))
module.exports = router
// This is the routing file
const express = require('express')
const router = express.Router()
router.post('/users/login'.async(req,res,next)=>{
try{
res.send('/users/login')}catch(err){
next(err)
}
})
module.exports = router
Copy the code
Simple demo put a question, if it is the development of the words, you can put the methods inside out, a module put a question, so easy to manage the interface.