Nodejs 创建web服务 静态资源服务器 get数据获取 post数据获取

NodeJs是通过官方提供的http模块来创建 web服务器的模块。通过几行简单的代码,就能轻松的手写一个web服务,从而对外提供 web 服务。

² 创建web服务基本步骤

①、导入http模块    

const http = require('http')

②、创建web服务对象实例

const server = http.createServer()

③、绑定监听客户端请求事件request

server.on('request', (request, response) => {})

 

request: 接受客户端请求对象,它包含了与客户端相关的数据和属性

   request.url      客户端请求的uri地址

   request.method  客户端请求的方式 getpost

   req.headers   客户端请求头信息

response:服务器对客户端的响应对象

  # 设置响应头信息 ,用于响应时有中文时乱码解决处理

  response.setHeader('content-type', 'text/html;charset=utf-8')

  # 设置状态码

     res.statusCod = 200

  # 向客户端发送响应数据,并结束本次请求的处理过程

  res.end('hello world')

④、启动服务

server.listen(8080, () => {

   console.log('服务已启动')

})

静态资源服务器

  • 实现思路

客户端请求的每个资源uri地址,作为在本机服务器指定目录中的文件。通过相关模块进行读取文件中数据进行响应给客户端,从而实现静态服务器。

  • 实现步骤

①、导入需要的模块

const http = require('http')

const fs = require('fs')

const path = require('path')

const url = require('url')

②、使用http模块创建web服务器

const server = http.createServer()

③、将资源的请求uri地址映射为文件的存放路径

// 事件监听

server.on('request', (req, res) => {

   // 得到请求的uri

   let pathname = req.url

   pathname = pathname === '/' ? '/index.html' : pathname

if (pathname !== '/favicon.ico') {

     // 请求静态地址

     let filepath = path.join(__dirname, 'public', pathname)

   }

})

④、读取文件内容并响应给客户端

fs.readFile(filepath, (err, data) => {

if (err) {

         res.statusCode = 500

            res.end('服务器内部错误')

        }else{

            res.end(data)

        }

})

get数据获取方式

get数据通过地址栏使用query方式进行传递的数据 例?id=1&name=zhangsan

const http = require('http');

const url = require('url');

http.createServer((req, res) => {

// 获取地址栏中 query数据

let { query } = url.parse(req.url, true);

console.log(query);

}).listen(8080)

表单数据多数为post进行提交到服务器端。

const http = require('http');

const queryString = require('querystring');

http.createServer((req, res) => {

  

  let arr = [];

  // 数据接受中

  req.on('data', buffer => {

    arr.push(buffer);

  });

  // 数据传输结束了

  req.on('end', () => {

// 拼接接受到的所有数据

    let buffer = Buffer.concat(arr);

    let post = queryString.parse(buffer.toString())

    console.log(post);

  });

 

}).listen(8080)

 

右侧打赏一下 代码改变世界一块二块也是爱
原文地址:https://www.cnblogs.com/ht955/p/14188099.html