Node. js, Express, Mysql Summary 1

Source: Internet
Author: User
After reading Nodejs today, it seems quite acceptable. Let's share my experiences. First, Nodejs provides an environment that enables background code, such as linking databases and page jumps, to be completely written by JS .. After installation, the procedure is very simple and will not be detailed.

After reading Node. js today, it is quite easy to accept. Let's share my experiences.

 

First, Node. js provides an environment that enables background code, such as linking databases and page jumps, to be completely written by JS ..

 

 

After installation is complete, the procedure is very simple and will not be detailed.

 

First write a Hello World:

 

Create a file HELLO. js

 

 

console.log(Hello World!);

You can place it anywhere, for example, c: myTestHELLO. js.

 

 

Open cmd and locate c: myTest.

 

Run node HELLO. js;

 

OK, print Hello World! That's simple.

 

So what is Express?

 

I believe you must have used ssh. It is a Java EE Framework and Express is also a framework. However, this framework is similar to struts in ssh. It mainly provides a route function, that is, page Jump!

 

This does not need to be downloaded because it is equivalent to a node module or extension.

 

How to install it?

 

Or just now c: myTest, create a file in it

 

Package. json

 

 

{  name: helo-world,  version: 0.0.1,  private: true,  scripts: {    start: node app  },  dependencies: {    express: 3.1.0,    ejs: *,    mysql:*  }}

This means that a project named helo-world is created, and the project uses express, OK

 

 

Open cmd, locate c: myTest, execute the node install command, and explain that the command will automatically find the package. json file and then execute it. After that, you can find that there is an additional node_modules file in the folder.

There is express. Here, the myText folder has been created for this express project.

 

But how to run it? First, you must have an app. js file similar to the WEB. XML file in ssh.

 

 

/** * Module dependencies. */var express = require('express')  , http = require('http')  , path = require('path')  , mysql = require('./db');var app = express();app.configure(function(){  app.set('port', process.env.PORT || 3000);  app.set('views', __dirname + '/views');  app.set('view engine', 'ejs');  app.use(app.router);  app.use(express.static(path.join(__dirname, 'public')));});app.configure('development', function(){  app.use(express.errorHandler());});var employeeProvider= new EmployeeProvider('localhost', 27017);//Routes//indexapp.get('/', function(req, res){  });//list employeeapp.get('/employee/list', function(req, res) {    mysql.query('select * from users', function(err, result) {        if(!err){            res.render('employee_new', {data: result});        }            });});app.listen(process.env.PORT || 3000);

The first few lines of code, that is, several modules are introduced. These modules are provided by node. The http and path modules

 

Then, the app variables are the variables of the entire project, through which you can set some project configurations.

 

For example, set the listening port and base path.

 

 

app.set('view engine', 'ejs');

 

This Code indicates that node requires a page rendering module, and jade or ejs is usually used in node.

 

If you have used spring mvc before, you should know that the page rendering module replaces jsp, which is faster than jsp rendering, such as Velocity ..

 

Ejs also needs to be installed, but we have already written it in package. jso, so it has been installed with Express.

 

 

app.use(express.static(path.join(__dirname, 'public')));

 

This Code defines a public path. The files in this path are made public to the public. You can put some css or javascript files.

 

 

app.set('views', __dirname + '/views');

 

 

After specifying the view path, you can directly call the render (File Name) method to render.

 

 

app.configure('development', function(){  app.use(express.errorHandler());});

 

I have defined the project. In development mode, I want to use errorHandler () for error handling. This is provided by express, just like the errorAction of struts!

 

 

app.get('/', function(req, res){  req.send(Hi!);});

 

 

It is linked to the url. This method accepts the get type, and the url provides two req res requests and corresponding parameters for/access. For this code, the hi page is returned.

 

Next let's talk about how to use mysql. Of course, the mysql module also needs to be installed, but we have already installed it. For details, see the package. json file.

 

Write a db. js and seeting. js

 

var mysql = require('mysql'),    settings = require('../settings');var connection = mysql.createConnection({    host : settings.host,    port : settings.port,    database : settings.db_name,    user : settings.username,    password : settings.password});connection.connect();module.exports = connection;

module.exports = {   cookieSecret: 'myblog_mysql',   db_name: 'blog_mysql',   host: 'localhost',  username: 'root',  password: 'root'}; 

All these files can be understood. It means that the module I understand is a keyword, which is equivalent to return. It means that the data returned in this file is exports. When other files are called, you can use it directly without using new!

 

 

 

app.get('/employee/list', function(req, res) {    mysql.query('select * from users', function(err, result) {        if(!err){            res.render('employee_list', {data: result});        }            });});

 

This get method is to accept the path "employee/list" and then call mysql. query to query data. Note that the data is obtained through the callback method. You can see that most of the node Code has a callback function. It is estimated that js is related to a single thread.

 

Then, create a file named "employee_list.ejs" for "employee_list,

 

 

<% data.forEach(function(post, index){%>

<% = Post. name %>

<% }%>
Just like writing java code in jsp !!

 

 

Okay here, a simple demo of connecting to the database with node is finished, and it is not difficult for you. In the future, we will update node and express and hope to provide more support!

 

Express document http://expressjs.com/api.html

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.