1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

Section 2.13: Setting up for globally installed packages

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.79 MB, 334 trang )


In order to use the globally installed module, it needs to be on your path:

export PATH=$PATH:~/.npm-global-modules/bin



Now when you run npm install -g gulp-cli you will be able to use gulp.

Note: When you npm install (without -g) the prefix will be the directory with package.json or the current

directory if none is found in the hierarchy. This also creates a directory node_modules/.bin that has the

executables. If you want to use an executable that is specific to a project, it's not necessary to use npm install -g.

You can use the one in node_modules/.bin.



GoalKicker.com – Node.js Notes for Professionals



29



Chapter 3: Web Apps With Express

Parameter

path



Details

Specifies the path portion or the URL that the given callback will handle.



middleware



One or more functions which will be called before the callback. Essentially a chaining of multiple

callback functions. Useful for more specific handling for example authorization or error

handling.



callback



A function that will be used to handle requests to the specified path. It will be called like

callback(request, response, next), where request, response, and next are described below.



callback request An object encapsulating details about the HTTP request that the callback is being called to handle.

response



An object that is used to specify how the server should respond to the request.



next



A callback that passes control on to the next matching route. It accepts an optional error object.



Express is a minimal and flexible Node.js web application framework, providing a robust set of features for building

web applications.

The official website of Express is expressjs.com. The source can be found on GitHub.



Section 3.1: Getting Started

You will first need to create a directory, access it in your shell and install Express using npm by running npm

install express --save



Create a file and name it app.js and add the following code which creates a new Express server and adds one

endpoint to it (/ping) with the app.get method:

const express = require('express');

const app = express();

app.get('/ping', (request, response) => {

response.send('pong');

});

app.listen(8080, 'localhost');



To run your script use the following command in your shell:

> node app.js



Your application will accept connections on localhost port 8080. If the hostname argument to app.listen is

omitted, then server will accept connections on the machine's IP address as well as localhost. If port value is 0, the

operating system will assign an available port.

Once your script is running, you can test it in a shell to confirm that you get the expected response, "pong", from

the server:

> curl http://localhost:8080/ping

pong



You can also open a web browser, navigate to the url http://localhost:8080/ping to view the output



GoalKicker.com – Node.js Notes for Professionals



30



Section 3.2: Basic routing

First create an express app:

const express = require('express');

const app = express();



Then you can define routes like this:

app.get('/someUri', function (req, res, next) {})



That structure works for all HTTP methods, and expects a path as the first argument, and a handler for that path,

which receives the request and response objects. So, for the basic HTTP methods, these are the routes

// GET www.domain.com/myPath

app.get('/myPath', function (req, res, next) {})

// POST www.domain.com/myPath

app.post('/myPath', function (req, res, next) {})

// PUT www.domain.com/myPath

app.put('/myPath', function (req, res, next) {})

// DELETE www.domain.com/myPath

app.delete('/myPath', function (req, res, next) {})



You can check the complete list of supported verbs here. If you want to define the same behavior for a route and all

HTTP methods, you can use:

app.all('/myPath', function (req, res, next) {})



or

app.use('/myPath', function (req, res, next) {})



or

app.use('*', function (req, res, next) {})

// * wildcard will route for all paths



You can chain your route definitions for a single path

app.route('/myPath')

.get(function (req, res, next) {})

.post(function (req, res, next) {})

.put(function (req, res, next) {})



You can also add functions to any HTTP method. They will run before the final callback and take the parameters

(req, res, next) as arguments.

// GET www.domain.com/myPath

app.get('/myPath', myFunction, function (req, res, next) {})



Your final callbacks can be stored in an external file to avoid putting too much code in one file:

GoalKicker.com – Node.js Notes for Professionals



31



// other.js

exports.doSomething = function(req, res, next) {/* do some stuff */};



And then in the file containing your routes:

const other = require('./other.js');

app.get('/someUri', myFunction, other.doSomething);



This will make your code much cleaner.



Section 3.3: Modular express application

To make express web application modular use router factories:

Module:

// greet.js

const express = require('express');

module.exports = function(options = {}) { // Router factory

const router = express.Router();

router.get('/greet', (req, res, next) => {

res.end(options.greeting);

});

return router;

};



Application:

// app.js

const express = require('express');

const greetMiddleware = require('./greet.js');

express()

.use('/api/v1/', greetMiddleware({ greeting:'Hello world' }))

.listen(8080);



This will make your application modular, customisable and your code reusable.

When accessing http://:8080/api/v1/greet the output will be Hello world

More complicated example

Example with services that shows middleware factory advantages.

Module:

// greet.js

const express = require('express');

module.exports = function(options = {}) { // Router factory

const router = express.Router();

// Get controller

const {service} = options;

router.get('/greet', (req, res, next) => {



GoalKicker.com – Node.js Notes for Professionals



32



res.end(

service.createGreeting(req.query.name || 'Stranger')

);

});

return router;

};



Application:

// app.js

const express = require('express');

const greetMiddleware = require('./greet.js');

class GreetingService {

constructor(greeting = 'Hello') {

this.greeting = greeting;

}

createGreeting(name) {

return `${this.greeting}, ${name}!`;

}

}

express()

.use('/api/v1/service1', greetMiddleware({

service: new GreetingService('Hello'),

}))

.use('/api/v1/service2', greetMiddleware({

service: new GreetingService('Hi'),

}))

.listen(8080);



When accessing http://:8080/api/v1/service1/greet?name=World the output will be Hello, World

and accessing http://:8080/api/v1/service2/greet?name=World the output will be Hi, World.



Section 3.4: Using a Template Engine

Using a Template Engine

The following code will setup Jade as template engine. (Note: Jade has been renamed to pug as of December 2015.)

const express = require('express'); //Imports the express module

const app = express(); //Creates an instance of the express module

const PORT = 3000; //Randomly chosen port

app.set('view engine','jade'); //Sets jade as the View Engine / Template Engine

app.set('views','src/views'); //Sets the directory where all the views (.jade files) are stored.

//Creates a Root Route

app.get('/',function(req, res){

res.render('index'); //renders the index.jade file into html and returns as a response. The

render function optionally takes the data to pass to the view.

});

//Starts the Express server with a callback

app.listen(PORT, function(err) {

if (!err) {

console.log('Server is running at port', PORT);



GoalKicker.com – Node.js Notes for Professionals



33



} else {

console.log(JSON.stringify(err));

}

});



Similarly, other Template Engines could be used too such as Handlebars(hbs) or ejs. Remember to npm install the

Template Engine too. For Handlebars we use hbs package, for Jade we have a jade package and for EJS, we have an

ejs package.



EJS Template Example

With EJS (like other express templates), you can run server code and access your server variables from you HTML.

In EJS it's done using "<%" as start tag and "%>" as end tag, variables passed as the render params can be accessed

using <%=var_name%>

For instance, if you have supplies array in your server code

you can loop over it using

<%= title %>





    <% for(var i=0; i





  • <%= supplies[i] %>





  • <% } %>



    As you can see in the example every time you switch between server side code and HTML you need to close the

    current EJS tag and open a new one later, here we wanted to create li inside the for command so we needed to

    close our EJS tag at the end of the for and create new tag just for the curly brackets

    another example

    if we want to put input default version to be a variable from the server side we use <%=

    for example:

    Message:






    Here the message variable passed from your server side will be the default value of your input, please be noticed

    that if you didn't pass message variable from your server side, EJS will throw an exception. You can pass parameters

    using res.render('index', {message: message}); (for ejs file called index.ejs).

    In the EJS tags you can also use if , while or any other javascript command you want.



    Section 3.5: JSON API with ExpressJS

    var express = require('express');

    var cors = require('cors'); // Use cors module for enable Cross-origin resource sharing

    var app = express();

    app.use(cors()); // for all routes

    var port = process.env.PORT || 8080;

    app.get('/', function(req, res) {

    var info = {

    'string_value': 'StackOverflow',



    GoalKicker.com – Node.js Notes for Professionals



    34



Xem Thêm
Tải bản đầy đủ (.pdf) (334 trang)

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×