Skip to content

Instantly share code, notes, and snippets.

@xgqfrms-GitHub
Last active June 7, 2017 05:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms-GitHub/c9c6c54debdb5051f63af5f1273acb4f to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/c9c6c54debdb5051f63af5f1273acb4f to your computer and use it in GitHub Desktop.
express & routing

Express Routing

Express Routing

https://expressjs.com/en/guide/routing.html

    
var express = require('express')
var app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})



// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})



app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})



app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})



app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
  .put(function (req, res) {
    res.send('Update the book')
  })
  
  
    
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router
    
var birds = require('./birds')

// ...

app.use('/birds', birds)

https://expressjs.com/en/starter/basic-routing.html

    
// Respond with Hello World! on the homepage:

app.get('/', function (req, res) {
  res.send('Hello World!')
})
// Respond to POST request on the root route (/), the application’s home page:

app.post('/', function (req, res) {
  res.send('Got a POST request')
})
// Respond to a PUT request to the /user route:

app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
// Respond to a DELETE request to the /user route:

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})

demo

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment