ajax请求写到吐?秒懂node书写ajax响应报文

64 阅读5分钟

认识 node.js

    • node.js 也是js 不过 node的运行环境不在是浏览器 而是可以在浏览器以外的地方运行

命令行基本操作

    • 在某路径下搜索cmd 可在该路径下打开cmd终端
    • cls清屏
    • cd..返回上一级
    • 在cmd界面直接输入盘符 + :便可将路径切换到该盘
    • 在cmd界面输入 node + 当前目录下的js文件 便可以将该js代码在node里面运行
  • - 两次`ctrl + c`可以关闭进程
    

如何利用 node 执行 js 代码

  • 在cmd中输入node 然后回车 即进入node'控制台'
    • 缺点 不能够报错代码
    • 而且没有代码(可爱的)提示
  • 解决
    • 将js代码书写在js文件中 然后再文件目录下打开cmd终端 输入node + js文件

node 模块化开发

  • node 出现在Es6之前 所以node的模块化开发与 es6的模块化开发不同
  • 导出
    • 每个js文件创建自带一个module属性
      • 语法
        • 语法1: module.exports.type = value
        • 语法2: module.exports = 任意值 exports虽然是一个对象 但是其实是module对象内的一个属性 不过数据结构为对象类型 所以可以随意赋值
        • 语法3: exports.type = value
    exports.name = 'z'
    module.exports.age = 18
    module.exports = {name: 'dd',age:18}

node 内置模块 fs

  • fs (文件系统 files - system)
  • 文件读取
    • fs.readeFile(参数1:文件路径,参数二:编码类型默认为buffer, 参数三:回调函数) 异步读取
      • 回调函数接 回调函数有两个值
        • 读取失败 err(提示)
        • 读取成功 data(读取到的数据)
    • fs.readeFileSync(参数一:需要读取的文件的地址, 参数二: 编码类型)
      • 同步读取没有回调函数 需要一个变量接收速去到的数据
          let s = fs.readeFileSync('../index/1.txt','utf-8')
      
  • 文件写入(异步)
    • fs.writeFile(参数一:待写入文件,参数二:待写入内容,参数三,回调函数)
      • 回调函数有一个data参数
      • 写入规则
        • 参数内文件存在 则写入到该文件
        • 没有该文件 创建一个文件 然后写入 文件名为参数内书写 路径也为 参数书写路径

内置模块 path

  • node提供的操作路径相关的模块
    • path.resolve()
      • 接收多个参数
      • 将接收的路径碎片拼接到一起
    • path.parse()
      • 返回一个对象 { root: 根目录 dir:文件的当前路径 base:完整文件名 包括后缀名 ext: 后缀名 name:文件名 }

内置模块 url

  • 有很多方法(很多)
  • node内置的操作地址相关的模块
    • parse()接收两个参数 参数一为需要解析的地址 参数二为 是否深度解析
  • http
    • 协议
      • http
      • https
  • host
    • 域名加端口
  • port
    • 端口号
  • hostname
    • 域名
  • hash
    • 哈希值
  • search
    • 查询字符串
  • query
    • 路径
  • pathname
    • 完整路径名
  • path
    • 路径 包括参数
  • href
    • 完整URL

内置模块 http

  • node提供的给我们创建服务器相关的
  • 创建 一个服务器
    • http.createServer(function (req, res) {})

请求

  • 什么是请求?
    • 在js内部 原生ajax发送的算请求
    • html标签中 表单form img标签 link标签 script标签的src属性 都可以发送请求

利用原生node搭建简易服务器

  • 创建服务器一般分为三步
  • 1、创建服务器的第一步 需要引入 node的内置模块http
    • 使用commonjs方式引入
            let http = require('http')
    
  • 2、创建一个服务器
    • http内置模块内有一个创建服务器的方法http.createServer()
      • 该方法接收一个函数 (req, res) => {}
        • req为前端发送的请求体
        • res要返回给前端的响应体
        • 函数内为服务器主体代码
        let app = http.createServer(function (req, res) => {})
    
  • 3、监听一个端口
    • 通过listen方法监听一个端口
        app.listen(8888, () => console.log('端口已开启'))
    

1. 初始搭建

  • 完整创建
    let port = 8080
    //要使用的端口 0 ~ 65535
    let http = require('http')
    //导入http模块
    let app = http.createServer(function (req, res) {
        //code run here
    })
    //创建一个服务器
    app.listen(port, () => console.log('端口已开启:' port))
  1. 配置 html 已经 css文件 和js文件
  • 首先和约定 所有的静态文件的请求我们都以static开头
    • 我们知道 link标签和script标签都可以发送请求 以及浏览器 ajax等
    • 所以接下来
      • 在隔壁创建一个client文件夹
        • client内的view文件夹存放着index.html 和 list.html
        • client内的css文件夹内存放着index.css 和 list.css
        • client内的js文件夹内存放着index.js 和 list.js
      • 在接收到浏览器的请求时 返回对应的页面
      • 接收到页面内的文件请求(link 和 script)返回对应文件
      • 完成简单服务器
    let port = 8080
    //要使用的端口 0 ~ 65535
    let fs = require('fs')
    //导入文件系统 file - system
    let http = require('http')
    let url = require('url')
    //地址处理模块
    let path = require('path')
    //路径
    let app = http.createServer(function (req, res) {
    let { pathname, query } = url.parse(req.url, true)
    //将请求地址深度解析  并解构
    let { ext, base } = path.parse(pathname)
    //解构出ext 和 base ext为请求的文件的后缀名 base为完整文件名 pathname为请求地址
    let IndexUrl = '../client'
    if (/^\/static/.test(pathname)) {// 验证是否遵守约定
        if (ext === '.html') { //判断文件后缀名 根据请求文件后缀 在IndexUrl后拼接上不同的路径
            IndexUrl += '/view'
            //view内为html文件
        } else if (ext === '.css') {
            IndexUrl += '/css'
        }else if (ext === '.js') {
            IndexUrl += '/js'
        }
    }
    IndexUrl += '/' + base 
    //完整的请求包括请求地址 和请求文件全名
    fs.readFile(`${IndexUrl}`, 'utf-8', function (err, data) { 
        //读取对应文件
        if (err) return
        //若没有文件则终止程序
        res.end(data)
        //将读取的文件
    })
})
    //创建一个服务器
    app.listen(port, () => console.log('端口已开启:' port))

3. 接口和静态资源 && 4. 接受请求参数

  • 约定接口请求以api开头
let fs = require('fs')
let http = require('http')
let url = require('url')
let path = require('path')

let myServer = http.createServer((req, res) => {
    let { pathname, query } = url.parse(req.url, true)
    let { ext, base } = path.parse(pathname)
    let IndexUrl = '../client'
    if (/^\/static/.test(pathname)) {
        if (ext === '.html') {
            IndexUrl += '/view'
        } else if (ext === '.css') {
            IndexUrl += '/css'
        }else if (ext === '.js') {
            IndexUrl += '/js'
        }
    }
    IndexUrl += '/' + base
    fs.readFile(`${IndexUrl}`, 'utf-8', function (err, data) {
        if (err) return
        res.end(data)
    })
    if (/^\/api/.test(pathname)) {
        if(pathname === '/api/users/info' && req.method === 'GET') {
            let info = {
                code :1,
                message:5555,
                sss:{
                    name:'z',
                    age:18
                },
                your:query
            }
            res.end(JSON.stringify(info))
        }
        if(pathname === '/api/users/login' && req.method === 'POST') {
            req.on('data', (paramsStr) => {
                str += paramsStr
            })
            let str = ''
            req.on('end', (paramsStr) =>{
                if (req.headers['content-type'] === 'application/json') {
                    str = JSON.parse(str)
                }else if (req.headers['content-type'] === 'application/x-www-from-urlencoded') {
                    str = url.parse('?' + str,true).query
                }
                let info = {
                    code :1,
                    message:5555,
                    your: str
                }
                res.end(JSON.stringify(info))
            })
        }
    }
})