express

Created at 2016-09-29 Updated at 2016-09-29 Category 学习 Tag 后台

console

console 本意是控制台

console在前台运行,就是chrome devtoos的 console

console在后台运行,就是命令行界面

Http请求

HTTP 请求 = Verb + Path;
HTTP 请求 = get/post/… + /about

EXPRESS

  1. 什么是express?

    Node.js web application
    framework

    Nodejs 技术的 Web 应用用框架

    express 是后台框架

    React 是前端框架

  2. express的作用是什么?

    网络服务器 nginx 存储静态页面 html/css/js;

    数据库 mongodb 存储数据;

    express 根据请求 :

    • 查询数据库;

    • 把数据插入html模板 ;

  3. express 如何操作?

    $mkdir mi-express-api

    $cd mi-express-api

    $npm init ///将一个项目转换为node项目,生成packge.json,记录版本信息

    $npm install –save express ///下载express包

    express 代码是运行在服务器上

    什么是路由?router ?

    基本意思?

    根据 http 请求,决定哪个⻚页面面要显示示

    拓展意思?

    根据 http 请求,决定哪一一段代码要执行行

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var express = require('express') ////将express引入Js
    var app = express()
    app.get('/', function (req, res) { ///这部分是用来接收请求
    res.send('Hello World')
    })
    app.get('/xiaomi', function (req, res) { ////这部分是用来接收请求
    res.send('Hello xiaomi')
    })
    app.listen(3000)

    读取请求参数

    request=verb + path

    参数(parameters)作为path的一部分传给后台服务器,这样可以实现前台的请求传入后台代码中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    var express = require('express')
    var app = express()
    app.get('/', function (req, res) {
    res.send('console.log(req.params)')
    })
    app.listen(3000)

    curl

    通过curl发命令模拟Http请求进行测试.
    $curl –request GET localhost:3000/:name

    $curl –request POST localhost:3000/:name

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    var express = require('express')
    var app = express()
    app.get('/:name', function (req, res) {
    var result=req.params.name
    var page ="<html>"+
    "<body>"+
    "<h1>"+
    result+" "+"de Blog" +
    "</h1>"+
    "</body>"+
    "</html>"
    res.send(page)
    })
    app.post('/:name', function (req, res) {
    res.send("a post request received"+req.params.name)
    })
    app.listen(3000,function(){
    console.log('running on port 3000...plz visit http://localhost:3000')
    })

Table of Content

  1. console
  2. Http请求
  3. EXPRESS
  4. curl
Site by Mickey using Hexo & Random

Hide