"NodeJS"---Express configuration ejs Mongoose route, etc.

Source: Internet
Author: User

Express Create Project

Under command line:

Express Prj_name

CD prj_name && NPM Install

Ejs html

var // increased app.set (' views ', Path.join (__dirname, ' public/views ')); // set the template folder path, you can specify // add app.set (' View engine ', ' html '); // setting the template engine used

Configuring Port Monitoring

App.set (' env ', Process.env.NODE_ENV | | ' Development '); App.set (' Port ', App.config.server.port | | 3000);
Interpreting App.js

Create an express application after require:

var app = Express ();

This can stay in the app.js.

Configuration

Next is a large section of App.set and App.use:

//All environmentsApp.set (' Port ', Process.env.PORT | | 3000); App.set (' Views ', __dirname + '/views '); App.set (' View engine ', ' Jade '); App.use (Express.favicon ()); App.use (Express.logger (' Dev ') ; App.use (Express.bodyparser ()); App.use (Express.methodoverride ()); App.use (Express.cookieparser (' Your secret here ') ; App.use (Express.session ()); App.use (App.router); App.use (Require (' Less-middleware ') ({src: __dirname + '/public ')}); App.use (Express.static (Path.join (__dirname,' Public ')));//Development Onlyif(' development ' = = App.get (' env ')) {app.use (Express.errorhandler ());}

app.setTo set the environment variable, the first parameter is the name of the environment variable, the second parameter is the value, and in other places where you need to access the environment variable, you can use app.get it, such as the one above app.get(‘env‘) . Here are some of the built-in express environment variables:

    • envRun-time environment, default to Process.env.NODE_ENV or "development"
    • trust proxyActivates the reverse proxy, which is not active by default
    • jsonp callback nameModify the default? callback= 's JSONP callback name
    • json replacerCallback when JSON Replacer is replaced, default is NULL
    • json spacesThe number of spaces in the JSON response is 2 in the development environment and the production environment is 0
    • case sensitive routingThe case sensitivity of the route, the default is the off state, "/foo" and "/foo" are the same
    • strict routingStrict format of the route, by default "/foo" and "/foo/" are treated the same
    • view cacheTemplate caching, which is enabled by default in a production environment
    • view engineTemplate engine
    • viewsCatalog of templates

We used the last two, setting the template engine for the page display and the directory where the template was saved.

Setting App.use ([path], function) refers to the intermediate function when the access prefix is executed, which is not specified in the preceding code, which means that the path function path intermediate function is executed when the path to the default prefix is accessed / function . For example, in the code above

App.use (Require (' Less-middleware ') ({src: __dirname + '/public 'Public '));

When accessing a static file /stylesheets/style.css , the Less-middleware is executed first, then executed express.static , and returned public/stylesheets/style.css to the browser side.

app.use()The order of appearances is very important, and the order of use determines the priority of the intermediate function. For example express.logger() , usually the first one can record all requests. If you do not want to log requests for static files, you can put less-middleware and put them in app.use(express.static) logger front.

There is a app.configure () method in the previous version of Express, although this method is still retained, but it is recommended if instead:

if (' development ' = = App.get (' env '))

Because there will be a lot of configuration later, so we have to extract this part of the content into a separate file, create /config/express.coffee these configurations, and in app.js with require instead of this part of the code:

Require ('./config/express ') (app);

express.favicon(iconPath): Used to set the icon for the website and the path to the icon. If not specified, the default Express icon is used. Can be modified to:

App.use (Express.favicon (Path.join (__dirname, ' ... /public/img/favicon.ico ')))

express.bodyParser(): Parse the request content, support the parsing of JSON, application/x-www-form-urlencoded, multipart/form-data format data. In other words, Ajax and form send the request, will pass its processing, convenient to get the corresponding request value in req. It is also used to process file uploads in Express, which allows you to specify the path to which the uploaded file will be stored, such as:

App.use (Express.bodyparser ({uploaddir: './uploads '}))

express.methodOverride(): To support the HTTP method such as put, delete, but the client mates, including the corresponding _method parameters, such as:

<form action= '/users/1 ' >   ... <input type= "hidden" name= "_method" value= "put"/></form>

can correspond to:app.put(‘/users/:id‘, users.put)

app.use(express.cookieParser(‘your secret here‘));and app.use(express.session()); : is to support the session, in such a setting, the session will be encrypted stored in the client's cookie, but this program restarts after the session will not work, However, Express.session supports the persistence of the session, because the most used database for Express is MONGO, so the configuration to save the session with MONGO is given below. First, add a dependency to the Package.json connect-mongo :

"connect-mongo": "0.3.3"

Then introduce Connect-mongo in the Config/express.coffee and modify the settings of the express.session:

Mongostore = require (' Connect-mongo ') (Express) App.use express.session      ' 1234567890 '         New  mongostore        url:config.db,        ' sessions '

app.routeris the enhanced version of Connect router, which is used to process, and so on, the app.get app.post request processing settings, the corresponding function is called when the browser accesses the corresponding URL in these settings express.router . If it is not explicitly called, app.use(app.router) Express will be app.get(...) implicitly called when the first encounter such a setting, so this can not appear in the configuration item, but .use the order is critical, so the explicit call is better. For example use app.use(express.static(path.join(__dirname, ‘public‘))); , if the router does not appear, or is placed behind it, every time the server encounters a request will be to the hard disk to find a corresponding static file, will cause performance degradation

Start

The final code of the file is to start the server and output a log:

function () {  console.log (' Server listening on port ' + app.get (' Port ');});

It's going to remain in the app.js.



"NodeJS"---Express configuration ejs Mongoose route, etc.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.