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.
151 lines
2.0 KiB
Markdown
151 lines
2.0 KiB
Markdown
[TOC]
|
|
|
|
# Create Express JS project
|
|
|
|
[Home](../../README.md)
|
|
|
|
[Reference](https://expressjs.com/en/starter/installing.html)
|
|
|
|
Create a project skeleton
|
|
|
|
Option1 : Using basic `npm` step
|
|
|
|
```sh
|
|
$ mkdir myapp
|
|
$ cd myapp
|
|
|
|
$ npm init
|
|
|
|
$ npm install express --save
|
|
|
|
```
|
|
|
|
|
|
|
|
Option2 : Using `npx` express application generator.
|
|
|
|
```sh
|
|
$ mkdir myapp
|
|
$ cd myappnpm
|
|
$ npx express-generator
|
|
$ npm install
|
|
```
|
|
|
|
|
|
|
|
Bootstrapped project folders
|
|
|
|
```sh
|
|
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
|
|
|
|
```sh
|
|
$ code .
|
|
```
|
|
|
|
|
|
|
|
Validate the `./bin/www.js`. By default, server serve at port 3000
|
|
|
|
```javascript
|
|
|
|
var port = normalizePort(process.env.PORT || '3000');
|
|
app.set('port', port);
|
|
|
|
```
|
|
|
|
|
|
|
|
Add new route in `app.js` for *helloworld* routing
|
|
|
|
```javascript
|
|
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`
|
|
|
|
```javascript
|
|
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
|
|
|
|
```sh
|
|
$ npm start
|
|
...
|
|
> expressjs@0.0.0 start C:\dev\playground\expressJS
|
|
> node ./bin/www
|
|
```
|
|
|
|
|
|
|
|
Browse [localhost](http://localhost:3000). You should see the text in browser
|
|
|
|
```text
|
|
Express
|
|
Welcome to Express
|
|
```
|
|
|
|
|
|
|
|
Use *Postman* to execute 'POST', 'PUT' methods
|
|
|
|
[Postman json](./postman_collection.json)
|
|
|
|
# Create Login
|
|
|
|
# Create
|
|
|