In the first part I am explaining how to do export and import using js.
here is my sample module ‘myutile.js‘
const myMethod1 = () => { console.log('Hi 1') } const myMethod2 = () => { console.log('Hi 2') } const myData = { name:'myname', age:22 } module.exports = { myMethod1, myMethod2, myData };
we can import all from the above module
var access1 = require('./myutile'); access1.myMethod1(); access1.myMethod2(); console.log(access1.myData);
output:
And also we can import only the specific function/data . for example I need to import only the `myMethod2()` and `myData` from the module
var m2 = require('./myutile').myMethod2; var data = require('./myutile').myData; m2(); console.log(data);
output:
Using Typescript
sample module ‘myutile.js’
export const myMethod1 = () => { console.log('Hi 1') } export const myMethod2 = () => { console.log('Hi 2') } export const myData = { name: 'myname', age: 22 } export default { myMethod1, myMethod2, myData };
import allUtiles from './myutile'; allUtiles.myMethod1(); allUtiles.myMethod2(); console.log(allUtiles.myData);
output
import * as allUtiles from './myutile'; allUtiles.myMethod2(); allUtiles.myMethod1(); console.log(allUtiles.myData);
output
import {myMethod1,myData} from './myutile'; myMethod1(); console.log(myData);
Using the express generator tool we can quickly and easy create an application skeleton.
Install express generater
npm install express-generator -g
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
It will create the folder structure and some required files
Go inside your app folder and execute npm install
It is ready to start the server
ref : https://expressjs.com/en/starter/generator.html
Click the debugger button located in the left side tool bar
Now you can see the debugger window, Click the setting icon and select Nodejs from the list
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
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.
Add break point in your code
Click the debugging button
Open your browser and hit the url
For downloading visual studio code IDE – click here
Create a new with nodejs and express (check this post for how to create node express project)
Pr-requirements
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
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/
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); ...
Move the rout definition from the index.js or app.js
Folder 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;