Skip to content

Instantly share code, notes, and snippets.

@abernier
Last active December 27, 2019 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abernier/a4fc97b892cb0bc1b81b1e548b3b8149 to your computer and use it in GitHub Desktop.
Save abernier/a4fc97b892cb0bc1b81b1e548b3b8149 to your computer and use it in GitHub Desktop.

Express controllers/routes conventions

HTTP Verb Path Controller#Action Used for
GET /photos photos#index display a list of all photos
PUT /photos/:id/valid OR /photos/valid photos#validate tell whether the passed data are valid (204 or 422)
HEAD /photos/:id OR /photos?people=Sam photos#exist tell whether that photo exists (204 or 404)
GET /photos/new photos#new return an HTML form for creating a new photo
POST /photos photos#create create a new photo
GET /photos/:id photos#show display a specific photo
GET /photos/:id/edit photos#edit return an HTML form for editing a photo
PATCH/PUT /photos/:id photos#update update a specific photo
DELETE /photos/:id photos#destroy delete a specific photo

see: https://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

const express = require('express')
const app = express()
app.use('/photos', require ('./routes/photos.js'))
app.listen(3000)
exports.index = (req, res, next) => {/*...*/}
exports.validate = (req, res, next) => {/*...*/}
exports.exist = (req, res, next) => {/*...*/}
exports.new = (req, res, next) => {/*...*/}
exports.create = (req, res, next) => {/*...*/}
exports.show = (req, res, next) => {/*...*/}
exports.edit = (req, res, next) => {/*...*/}
exports.update = (req, res, next) => {/*...*/}
exports.destroy = (req, res, next) => {/*...*/}
const express = require('express')
const router = express.Router()
const controller = require('../controllers/photos.js');
router.get('/', controller.index);
router.put('/valid', controller.validate)
router.put('/:id/valid', controller.validate)
router.head('/:id', controller.exist)
router.get('/new', controller.new);
router.post('/', controller.create);
router.get('/:id', controller.show);
router.get('/:id/edit', controller.edit);
router.put('/:id', controller.update);
router.delete('/:id', controller.destroy);
module.exports = router
@abernier
Copy link
Author

abernier commented Dec 22, 2019

As HTML <form>'s method can only be GET/POST, method-override can be handy :

// app.js
const methodOverride = require('method-override')

app.use(methodOverride('_method'))

app.delete('/cats/:id', function () {});
<form action="/cats/123?_method=DELETE" method="POST">
  ...
</form>

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