Express Archives - wiki

Nodejs Express application generator

Using the express generator tool we can quickly and easy create an application skeleton.

Install express generater

npm install express-generator -g

1installing-express-1generator

Use express -h for help

express -h

  Usage: express [options] [dir]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -e, --ejs           add ejs engine support (defaults to jade)
        --hbs           add handlebars engine support
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git           add .gitignore
    -f, --force         force on non-empty directory

Creating Express application with express generator

syntax

express <options> <application_name>

eg

express myapp

2-express-generater-my-app-1

It will create the folder structure and some required files

3-express-generater-my-appfolderstruct

Go inside your app folder and  execute npm install

after-executing-npm-install

It is ready to start the server

runninf-the-server

 

 

ref : https://expressjs.com/en/starter/generator.html

 

By bm on October 5, 2016 | NodeJs | A comment?
Tags: , ,

Nodejs Express Debugging using Visual Studio Code

Click the debugger button located in the left side tool bar

setting debugger

Now you can see the debugger window, Click the setting icon and select Nodejs from the list

setting debugger

It will open (Create) a  launch.json, make sure that the program path locating to your app entry point file ( “program”: “${workspaceRoot}/index.js” ) ( in my case it is index.js in your case may be it is app.js or other). Save the file using Ctrl+S

setting debugger

In the bellow screen you can see the automatically created launch configuration file ‘launch.json’

Open your package.js, check the start script is there or not, if it is not there please add it.

setting debugger

Add break point in your code

setting debugger

Click the debugging button

setting debugger

Open your browser and hit the url

setting debugger

 

 

For downloading visual studio code IDE – click here

 

By bm on August 19, 2016 | Express, NodeJs | A comment?
Tags: , , ,

Nodejs Express GET POST Multipart request handling example

Nodejs Express GET POST Multipart request handling example

Create a new with nodejs and express (check this post for how to create node express project)

Pr-requirements

  1. create an empty folder in root of your application
  2. install requires node packages (I have added all the node packages in package.json so you can simply run npm install it will take care of this)

index.js this is my app entry point.

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

app.use(express.static('public'));

//Routes
app.use(require('./routes'));

//app.use("/user",require('./routes'));  //http://127.0.0.1:8000/user  http://127.0.0.1:8000/user/about


var server = app.listen(8000, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("Server started.. (listening at http://%s:%s)", host, port)

})

routes.js :- I have made a separate rout file that’s why the routs.js file (Check this post for how to make separate rout file) otherwise you can directly add this code into your entry point file (in my case index.js)

I am using the multer node package for handing multipart request

var express = require('express');
var router = express.Router();


var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

var multer = require('multer')
var upload = multer({ dest: './uploads/' });

//middle ware that is specific to this router
router.use(function timeLog(req, res, next) {
    //console.log('Time: ', Date.now());
    next();
});

//Home page
router.get('/', function (req, res) {
    res.sendFile(__dirname + "/" + "home.htm");
})

//processing GET request
router.get('/process_get', function (req, res) {

    // Prepare output in JSON format
    response = {
        first_name: req.query.first_name,
        last_name: req.query.last_name,
        message: 'Result from a GET request'
    };
    console.log(response);
    res.end(JSON.stringify(response));
})

//processing POST Request
router.post('/process_post', urlencodedParser, function (req, res) {

    // Prepare output in JSON format
    response = {
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        message: 'Result from a POST request'
    };
    console.log(response);
    res.end(JSON.stringify(response));
})

//Multipart request (Accept one file where the name of the form field is named photo)
router.post('/file_upload', upload.single('photo'), function (req, res) {

    console.log(req.body) // form fields

    //console.log(req.body.first_name)
    //console.log(req.body.last_name)

    console.log(req.file) // form files
    res.status(204).end()
});

module.exports = router;

home.html

<html>
    <body>

        <div style="width:400px;">
            <h3>Submit form using GET request</h3>	
            <form action="process_get" method="GET">
                First Name: <input type="text" name="first_name">  <br />
                Last Name:  <input type="text" name="last_name">   <br />
                <input type="submit" value="Submit">
            </form>

            <hr />

            <h3>Submit form using POST request</h3>
            <form action="process_post" method="POST" >
                First Name: <input type="text" name="first_name"> <br />
                Last Name:  <input type="text" name="last_name">  <br />
                <input type="submit" value="Submit">
            </form>

            <hr />

            <h3>File Upload:</h3>
            Select a file to upload: <br />
            <form action="file_upload" method="POST"  enctype="multipart/form-data">
                First Name: <input type="text" name="first_name">  <br />
                Last Name:  <input type="text" name="last_name">   <br />
                Photo :     <input type="file" name="photo" size="50" /> <br /><br />
                <input type="submit" value="Submit" />
            </form>

            <hr />
        </div>
    </body>
</html>

package.json

{
    "name": "sample app",
    "version": "0.0.1",
    "description": "express get post multipart tutorial",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "bm",
    "license": "ISC",
    "dependencies": {
        "body-parser": "^1.15.2",
        "cookie-parser": "^1.4.3",
        "express": "^4.14.0",
        "multer": "^1.2.0"
    }
}

It is ready open your browser and test it

nodefileupload

You can see the file is uploaded, but it is using some random name for the file.

For changing file name we can make a small configuration changes in routs.js. Insted of  ‘var upload = multer({ dest: ‘./uploads/’ });’ add the new configuration settings

.....
.....

var multer = require('multer')
//var upload = multer({ dest: './uploads/' });

var storage = multer.diskStorage({
    destination: function (request, file, callback) {
        callback(null, './uploads/');
    },
    filename: function (request, file, callback) {
        console.log(file);
        callback(null, file.originalname)
    }
});

var upload = multer({ storage: storage });

.....
.....

 

 

ref :

https://wiki.workassis.com/installing-express-with-nodejs/

https://wiki.workassis.com/nodejs-express-separate-routes/

https://www.npmjs.com/package/multer

Allow CORS in Express/Node.js?

Open index.js (in your case it may be app.js or server.js) and set the request header

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

//CORS support settings
app.use(function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    next();
});


...

....

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.use('/api/user', user);

...

 

By bm on August 17, 2016 | Express, NodeJs | A comment?
Tags: , ,

Nodejs Express separate routes

Move the rout definition from the index.js or app.js

Folder structure

node structure

index.js file

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

app.use(express.static('public'));

//Routes
app.use(require('./routes'));  //http://127.0.0.1:8000/    http://127.0.0.1:8000/about

//app.use("/user",require('./routes'));  //http://127.0.0.1:8000/user  http://127.0.0.1:8000/user/about

//you can create more routs
//app.use("/admin",require('./adminroutes')); //http://127.0.0.1:8000/admin http://127.0.0.1:8000/admin/about

var server = app.listen(8000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

})

 

routes.js

var express = require('express');
var router = express.Router();

//Middle ware 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('home page');
});

// Define the about route
router.get('/about', function(req, res) {
  res.send('About us');
});


module.exports = router;

you can add more routs like admin routs (*i am not added this in my project so it will not see int the above folder structure)

adminroutes.js

var express = require('express');
var router = express.Router();

//Middle ware 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('Admin dash board');
});

// Define the about route
router.get('/profile', function(req, res) {
  res.send('About profile');
});


module.exports = router;

 

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

By bm on August 2, 2016 | Express, NodeJs | A comment?
Tags: , ,