You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.0 KiB
2.0 KiB
[TOC]
Create Express JS project
Create a project skeleton
Option1 : Using basic npm step
$ mkdir myapp
$ cd myapp
$ npm init
$ npm install express --save
Option2 : Using npx express application generator.
$ mkdir myapp
$ cd myappnpm
$ npx express-generator
$ npm install
Bootstrapped project folders
C:.
| app.js
| package-lock.json
| package.json
|
+---bin
| www
|
+---public
| +---images
| +---javascripts
| \---stylesheets
| style.css
|
+---routes
| index.js
| users.js
|
\---views
error.jade
index.jade
layout.jade
Launch vscode IDE
$ code .
Validate the ./bin/www.js. By default, server serve at port 3000
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
Add new route in app.js for helloworld routing
var helloworldRouter = require('./routes/helloworld');
//...
app.use('/', indexRouter);
app.use('/users', usersRouter);
// new routing to helloworld
app.use('/helloworld', helloworldRouter);
Create new routing for ./routes/helloworld.js
var express = require('express');
var router = express.Router();
// GET method
router.get('/', function (req, res) {
res.send('Hello World!')
})
// POST method
router.post('/', function (req, res) {
res.send('Got a POST request')
})
// PUT method
router.put('/user', function (req, res) {
res.send('Got a PUT request at helloworld/user')
})
module.exports = router;
Run the server
$ npm start
...
> expressjs@0.0.0 start C:\dev\playground\expressJS
> node ./bin/www
Browse localhost. You should see the text in browser
Express
Welcome to Express
Use Postman to execute 'POST', 'PUT' methods