Node系列学习之Node基础

213 阅读2分钟

这是我参与更文挑战的第7天,活动详情查看:更文挑战

新建一个文件夹 npm init -y

创建http服务

const http= require('http')
const server = http.createServer((req,res) => {
  // 设置响应头
  res.setHeader('Content-Type','application/json')
  // 返回数据
  res.end('<h1>返回内容</h1>')
})
// 监听端口
server.listen(1996)
console.log('OK');

处理GET请求

const http= require('http')
const querystring = require('querystring')
const server = http.createServer((req,res) => {
  res.setHeader('Content-Type','application/json')
  console.log('method', req.method)
  const url = req.url
  console.log('url', url);
  // 通过querystring.parse将类似a=1&b=2&c=3 转换为 {a:1,b:2,c:3}
  req.query = querystring.parse(url.split('?')[1])
  console.log('query', req.query);
  res.end(JSON.stringify(req.query))
})
server.listen(1996)
console.log('OK');

处理POST请求

const http = require('http')
const server = http.createServer((req,res) => {
  // 通过req.method来判断请求类型
  if(req.method == 'POST') {
    console.log('req content-type: ', req.headers['content-type']);
    // 接受数据
    let postData = ''
    // 监听req的data与end事件,当data时间传输完成后会触发req的end事件
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      console.log('postData: ', postData);
      res.end('Hello World! ')
    })
  }
})
server.listen(1996)
console.log('OK');

综合一下

const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
  const method = req.method
  const url = req.url
  const path = req.url.split('?')[0]
  const query = querystring.parse(url.split('?')[1])
  // 设置响应头
  res.setHeader('Content-Type', 'application/json')
  // 返回的数据
  const resData = {
    method,
    url,
    path,
    query
  }
  // 分别对GET和POST进行处理
  if(method == 'GET') {
    res.end(JSON.stringify(resData))
  }
  if(method == 'POST') {
    let postData = ''
    req.on('data', chunk => {
      postData += chunk.toString()
    })
    req.on('end', () => {
      resData.postData = postData
      res.end(JSON.stringify(resData))
    })
  }
})
server.listen(1996)
console.log('OK')

正式开搞

搭建开发环境

  • 初始化npm环境 npm init -y

  • 在主目录下添加 bin文件夹,并创建 www.js , 然后修改 package.json,更改入口文件地址

    {
      "name": "node-blog",
      "version": "1.0.0",
      "description": "",
      "main": "bin/www.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }
    
  • www.jsapp.js

    // www.js
    const http = require('http')
    
    const PORT = 1996
    
    const serverHandle = require('../app.js')
    
    const server = http.createServer(serverHandle)
    
    server.listen(PORT)
    

    新建app.js, 与 bin 目录同级

    // app.js
    const serverHandle = (req, res) => {
      res.setHeader('Content-Type', 'application/json')
      const resData = {
        name: 'Tmier',
        site: 'xxx.com'
      }
      res.end(JSON.stringify(resData))
    }
    module.exports = serverHandle
    
  • 安装插件

    npm i nodemon cross-env --save-dev
    

    安装成功之后, 在 package.json 中新添加一条命令

      "scripts": {
    	...
        // 设置环境变量为dev 使用nodemon启动www.js
        "dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js"
      }
    

    然后可以运行使用:

    npm run dev
    // nodemon 可以监听js文件的变动且自动更新
    

    开发环境搭建好了,明天开始搞路由~

    因为确实是刚开始学习Node,所以笔记略显稚嫩, 一步步来吧, 加油~