Node Js 建立项目和调试

  1. 引入 required 模块:我们可以使用 require 指令来载入 Node.js 模块。
  2. 创建服务器:服务器可以监听客户端的请求,类似于 Apache 、Nginx 等 HTTP 服务器。
  3. 接收请求与响应请求 服务器很容易创建,客户端可以使用浏览器或终端发送 HTTP 请求,服务器接收请求后返回响应数据。
    这里写图片描述

以上代码我们完成了一个可以工作的 HTTP 服务器。
使用 node 命令执行以上的代码:

liuMacBook-Pro:NodeJS hezi$ cd example/
liuMacBook-Pro:example hezi$ node example.js
服务器运行在 http://127.0.0.1:3000/

NPM使用(国内镜像cnpm使用,速度要快很多)

$ npm install -g cnpm --registry=https://registry.npm.taobao.org

alias cnpm="npm --registry=https://registry.npm.taobao.org \
--cache=$HOME/.npm/.cache/cnpm \
--disturl=https://npm.taobao.org/dist \
--userconfig=$HOME/.cnpmrc"

# Or alias it in .bashrc or .zshrc
$ echo '\n#alias for cnpm\nalias cnpm="npm --registry=https://registry.npm.taobao.org \
  --cache=$HOME/.npm/.cache/cnpm \
  --disturl=https://npm.taobao.org/dist \
  --userconfig=$HOME/.cnpmrc"' >> ~/.zshrc && source ~/.zshrc

NPM是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,常见的使用场景有以下几种:
* 允许用户从NPM服务器下载别人编写的第三方包到本地使用。
* 允许用户从NPM服务器下载并安装别人编写的命令行程序到本地使用。
* 允许用户将自己编写的包或命令行程序上传到NPM服务器供别人使用。

如果你安装的是旧版本的 npm,可以很容易得通过 npm 命令来升级,命令如下:

$ sudo npm install npm -g
/usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
npm@2.14.2 /usr/local/lib/node_modules/npm
使用淘宝镜像的命令:
cnpm install npm -g

全局安装与本地安装

npm 的包安装分为本地安装(local)、全局安装(global)两种,从敲的命令行来看,差别只是有没有-g而已,比如

npm install express      # 本地安装
npm install express -g   # 全局安装

更新模块

$ npm update express

搜索模块

$ npm search express

REPL 命令

ctrl + c - 退出当前终端。

ctrl + c 按下两次 - 退出 Node REPL。

ctrl + d - 退出 Node REPL.

向上/向下 键 - 查看输入的历史命令

tab 键 - 列出当前命令

.help - 列出使用命令

.break - 退出多行表达式

.clear - 退出多行表达式

.save filename - 保存当前的 Node REPL 会话到指定文件

.load filename - 载入当前 Node REPL 会话的文件内容。

Express 使用

下面一段是取自官网的例子:

这里写图片描述

Express application generator

Use the application generator tool, express-generator, to quickly create an application skeleton.
使用自动构建工具,express-generator 可以快速的建立项目

The express-generator package installs the express command-line tool. Use the following command to do so:
执行命令如下:

$ npm install express-generator -g

Display the command options with the -h option:
查看参数命令:

$ express -h

Usage: express [options] [dir]

Options:

    -h, --help          output usage information
        --version       output the version number
    -e, --ejs           add ejs engine support
        --hbs           add handlebars engine support
        --pug           add pug engine support
    -H, --hogan         add hogan.js engine support
    -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
    -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

For example, the following creates an Express app named myapp. The app will be created in a folder named myapp in the current working directory and the view engine will be set to Pug:
创建一个myapp的项目:

$ express --view=pug myapp
// 模板是ejs,默认的是jade
express -t ejs microblog

输出信息:

create : myapp
   create : myapp/package.json
   create : myapp/app.js
   create : myapp/public
   create : myapp/public/javascripts
   create : myapp/public/images
   create : myapp/routes
   create : myapp/routes/index.js
   create : myapp/routes/users.js
   create : myapp/public/stylesheets
   create : myapp/public/stylesheets/style.css
   create : myapp/views
   create : myapp/views/index.pug
   create : myapp/views/layout.pug
   create : myapp/views/error.pug
   create : myapp/bin
   create : myapp/bin/www
Then install dependencies:
$ cd myapp
$ npm install

On MacOS or Linux, run the app with this command:
Mac和Linux用户可以执行如下命令:

$ DEBUG=myapp:* npm start

On Windows, use this command:
Windows可以用如下命令:

> set DEBUG=myapp:* & npm start

Then load http://localhost:3000/ in your browser to access the app.
在浏览器里输入http://localhost:3000/访问该项目。

The generated app has the following directory structure:
生成的结构如下:

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.pug
    ├── index.pug
    └── layout.pug

7 directories, 9 files

使用Express

$ npm install -g supervisor

安装 supervisor 。使用 supervisor 命令启动 app.js:

$ supervisor app

这里写图片描述

中间遇到的一些问题:

引用中间是有先后顺序的

1、express4.x connect-flash出错

 var settings = require('./settings'); //配置信息
 var flash = require('connect-flash');
 var session = require('express-session');

 app.use(session({
 secret: settings.cookieSecret, //加密
 key: settings.db, //cookie nam
 cookie: {maxAge: 60000},
 resave: false,
 saveUninitialized: true,
 }));

 app.use(flash());

 // set flash
 app.use(function (req, res, next) {
     res.locals.errors = req.flash('error');
     res.locals.infos = req.flash('info');
     next();
 });

connect-flash 要用到 session,所以在用 app.use(flash()); 要先引入

app.use(session({
    secret: settings.cookieSecret, //加密
    key: settings.db, //cookie nam
    cookie: {maxAge: 60000},
    resave: false,
    saveUninitialized: true,
}));

之后要想输出req.flash信息

 app.use(function (req, res, next) {
     res.locals.errors = req.flash('error');
     res.locals.infos = req.flash('info');
     next();
 });

在要输出的地方
这里写图片描述

2、express-session 和 connect-mongo

secret 用来防止篡改 cookie,key 的值为 cookie 的名字,通过设置 cookie 的 maxAge 值设定 cookie 的生存期,这里我们设置 cookie 的生存期为 30 天,设置它的 store 参数为 MongoStore 实例,把会话信息存储到数据库中,以避免丢失。在后面的小节中,我们可以通过 req.session 获取当前用户的会话对象,获取用户的相关信息。
app.use(session({
                secret: settings.cookieSecret,
                key: settings.db,//cookie name
                cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
                store: new MongoStore({
                    url: 'mongodb://localhost/blog'
                    //db: settings.db,
                    //host: settings.host,
                    //port: settings.port
                })
            }));

3、POST请求之后,取不到前端的数据

body-parser这个中间件

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

这两行配置代码写在路由配置之前,例如

var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json()); //中间件
app.use(bodyParser.urlencoded({ extended: false })); //中间件
//以下为路由配置
var routes = require('./routes/index');
var users = require('./routes/users');
...other code...

调试nodejs

则可通过下述命令打开调试信息:

DEBUG=sample-app node ./bin/www

可通过逗号隔开的名字列表来指定多个调试命名空间,如下所示:

$ DEBUG=http,mail,express:* node index.js
// npm安装目录
/usr/local/lib/node_modules

安装调试工具
全局安装 node-inspector

sudo npm install -g node-inspector

第二步: 输入如下指令启动项目

node --debug www

这里写图片描述

第三步

node-inspector

这里写图片描述

第四步: 选择一款支持 node-inspector 的浏览器,你可以选择 chrome 或者 firefox

这里写图片描述

发布了14 篇原创文章 · 获赞 17 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/liu305088020/article/details/76088900