Node.js知识点总结(以node.js+mongodb+html实现简易报名系统为例)

一、学习资料

Node.JS-黑马程序员

nodeJS学习笔记

二、知识分类

1、模块系统
  • 在NodeJS中,一般将代码合理拆分到不同的JS文件中,每一个文件就是一个模块,而文件路径就是模块名
  • 主模块app.js是程序的入口文件
  • requireexportsmodule变量
    • require函数用于在当前模块中加载和使用别的模块,传入一个模块名,返回一个模块导出对象。模块名可使用相对路径(以./开头),或者是绝对路径(以/C:之类的盘符开头)
    • exports对象是当前模块的导出对象,用于导出模块公有方法和属性。别的模块通过require函数使用当前模块时得到的就是当前模块的exports对象
    • 通过module对象可以访问到当前模块的一些相关信息,但最多的用途是替换当前模块的导出对象
    • exportsmodule.exports的区别:
      ① 每个模块中都有一个module对象, module对象中有一个exports对象
      ② 我们可以把需要导出的成员都挂载到module.exports接口对象中,也就是module.exports.xxx = xxx的方式
      ③ 但是每次写太多了就很麻烦,所以Node为了简化代码,就在每一个模块中都提供了一个成员叫exportsexports === module.exports结果为true,所以完全可以exports.xxx = xxx
      ④ 当一个模块需要导出单个成员的时候必须使用module.exports = xxx的方式,使用exports = xxx不管用,因为每个模块最终return的是module.exports,而exports只是module.exports的一个引用,所以exports即使重新赋值,也不会影响module.exports
      ⑤ 有一种赋值方式比较特殊:exports = module.exports这个用来新建立引用关系的
  • 举例
var Student = require('./student');   // 导入模块student.js`

module.exports = router;  // 导出当前文件模块,并命名为router

// 查找学生所有信息
exports.find = function (callback) {
    
    
    fs.readFile(dbPath,'utf8',function (err,data) {
    
    
        if(err){
    
    
            return callback(err);
        }
        callback(null,JSON.parse(data).students);
    })
};

总结:

  • 导出单个成员:exports.xxx = xxx;
  • 导出多个成员:module.exports 或者 modeule.exports = {};
2、MongoDB数据库

MongoDB安装、启动服务、常用命令

在node.js中通过mongoose来使用MongoDB数据库。

下载mongoose:

npm install mongoose

连接:

const mongoose = require('mongoose');
// mongodb://localhost:27017/数据库名称 为固定使用方式,用来启动数据库服务
mongoose.connect('mongodb://localhost:27017/test', {
    
    useNewUrlParser: true}); // 域名后面的test为数据库名,若没有该数据库,则在进行第一条数据操作的时候会创建该数据库

// 定义文档结构
const kittySchema = new mongoose.Schema({
    
    
  name: String
});

// 将Schema架构编译成模型
const Kitten = mongoose.model('Kitten', kittySchema);

// 至此,通过Kitteen创建对象,即可使用,例如
const silence = new Kitten({
    
     name: 'Silence' });
console.log(silence.name); // 'Silence'

mongoose使用参考博客:添加链接描述

3、路由
// express提供了路由,先创建一个路由容器
var router = express.Router();

// 报名操作,输入姓名和学号
// 获取客户端数据,并保存在数据库中
router.post('/',function (req,res) {
    
    
    console.log(req.body);

    new Student(req.body).save(function (err) {
    
    
        if(err){
    
    
            return res.status(500).send("server error.")
        }
        res.redirect('/show');
    });
});

// 显示报名信息
router.get('/show',function (req,res) {
    
    
    // executes, passing results to callback
    Student.find(function (err,students) {
    
    
        if(err){
    
    
            return res.status(500).send("server error.")
        }

        // 第一个students渲染show.html页面; 第二个students同function传入的参数
        res.render('show.html',{
    
    students:students}); 
    });
});
4、项目环境配置
  • 初始化 npm init -y

  • 安装express npm install --save express

  • 安装art-template(res.render()的使用,访问views文件夹里面的文件) npm i --save art-template express-art-template

    • 配置:app.engine('html', require('express-art-template'));
    • 使用:
  app.get('/',function(req,res){
    
    
    // express默认会去views目录找index.html
    res.render('index.html',{
    
    
           title:'hello world'     
    });
})`
  • 配置静态资源 app.use(express.static('./public')); // 访问public文件夹里面的静态文件
    • 使用:
    <link rel="stylesheet" href="/style/basic.css"/>
    <link rel="stylesheet" href="/style/index.css"/>

目录结构:
在这里插入图片描述

  • 安装body-parser (POST获取客户端数据) npm install --save body-parser

    • 使用:
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({
    
     extended: false }))
// parse application/json 
app.use(bodyParser.json())
  • 安装mongoose(启动MongoDB服务后,才可以使用数据库进行增删查改) npm install mongoose
    API官方文档:添加链接描述

  • 安装bootstrap npm install bootstrap
    在线教程:添加链接描述

  • 导出模块接口 module.exports = router;

5、res.render()和res.send()

大多数情况下,渲染内容用res.render(),将会根据views中的模板文件进行渲染。

(需要安装模板引擎art-templateapp.engine('html',require('express-art-template'));

6、art-template模板语法

参考博客:模板引擎 – art-template

例如,循环输出的标准语法,

{
    
    {
    
    each target}} // 开始标识
  {
    
    {
    
    $index}} {
    
    {
    
    $value}}
{
    
    {
    
    /each}} // 结束标识
<table class="table table-striped">
                    <thead>
                    <tr>
                        <th>编号</th>
                        <th>姓名</th>
                        <th>学号</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {
   
   { each students }}
                    <tr>
                        <!--<td>{
    
    { $value.id }}</td>-->
                        <td>{
   
   { $index+1 }}</td>
                        <td>{
   
   { $value.name}}</td>
                        <td>{
   
   { $value.number}}</td>
                        <td>
                            <a href="/edit?id={
     
     { $value._id }}">修改</a>
                            <a href="/delete?id={
     
     { $value._id }}">删除</a>
                        </td>
                    </tr>
                    {
   
   { /each }}
                    </tbody>
                </table>

区别于jQuery的each()方法。

猜你喜欢

转载自blog.csdn.net/weixin_43973415/article/details/107968031