Liang2uv's blog Liang2uv's blog
首页
  • 前端文章

    • JavaScript
    • Vue
    • 面试总结
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 小程序笔记
    • TypeScript笔记
    • 数据结构笔记
    • mongoDB笔记
    • nginx笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
  • 网站
  • 资源
  • 关于
  • 作品集

Liang2uv

我也想成为前端大佬
首页
  • 前端文章

    • JavaScript
    • Vue
    • 面试总结
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 小程序笔记
    • TypeScript笔记
    • 数据结构笔记
    • mongoDB笔记
    • nginx笔记
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 分类
  • 标签
  • 归档
  • 网站
  • 资源
  • 关于
  • 作品集
  • 技术文档

  • GitHub技巧

  • Nodejs

    • nodejs递归读取所有文件
    • nodejs文件操作
    • nodejs服务器相关
      • 创建服务器
        • 初步
        • 绑定ip地址
      • 处理路径分发
      • 静态资源服务
        • 方法一
        • 方法二
      • 静态资源服务器封装
  • 博客搭建

  • 技术
  • Nodejs
Liang2uv
2019-10-06

nodejs服务器相关

# nodejs服务器相关

# 创建服务器

# 初步

var http = require("http");
http.createServer(function (request, response) {
    response.writeHead(200, { "Content-Type": "text/html" });
    response.write("<h1>Hello World</h1>");
    response.end();
}).listen(8888); // 监听8888端口
1
2
3
4
5
6

Content-Type说明

  • text/html : HTML格式
  • text/plain :纯文本格式
  • application/json : JSON数据格式
  • application/x-www-form-urlencoded : form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
  • multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
  • application/octet-stream : 二进制流数据(如常见的文件下载)

# 绑定ip地址

http.createServer((req, res)=> {
    res.end('hello');
}).listen(8888, '192.168.1.101', ()=>{
    console.log('server http://192.168.1.101:8888 is running...');
});
1
2
3
4
5

入站规则建立:控制面板 -> 系统和安全 -> 防火墙 -> 高级设置 -> 入站规则 -> 新建规则 -> 端口

# 处理路径分发

/**
 * 处理路径分发
 */
const http = require('http');

// 绑定ip地址
http.createServer((req, res) => {
    // 指定返回的编码格式是utf-8
    res.writeHead(200, { "Content-Type": "text/plain;charset=utf-8" });
    // 路径处理
    const reqUrl = req.url;
    if (reqUrl === '/') {
        res.end('根路径');
    } else if (reqUrl === '/index') {
        // write方法可以写多次
        res.write('hello\n');
        res.write('你好啊\n');
        res.end();
    } else {
        res.end('404 找不到资源');
    }
}).listen(8888, '192.168.1.101', () => {
    console.log('server http://192.168.1.101:8888 is running...');
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 静态资源服务

# 方法一

const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('./util/mime.json');

// 创建服务器
http.createServer((req, res) => {
    // 路径处理
    res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
    const reqUrl = req.url;
    if (reqUrl === '/') {
        res.end('根路径');
    } else if (reqUrl === '/index') {
        readFile('index.html', res);
    } else if (reqUrl === '/list') {
        readFile('list.html', res);
    } else {
        res.end('404 找不到资源');
    }
}).listen(8888, '192.168.1.101', () => {    // 绑定ip地址
    console.log('server http://192.168.1.101:8888 is running...');
});

// 根据路径读取文件内容,并且响应到客户端
function readFile(fileName, res) {
    fs.readFile(path.join(__dirname, 'www', fileName), (err, data) => {
        if (err) {
            res.end(err);
        } else {
            res.end(data);
        }
    });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

# 方法二

const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('./util/mime.json');

// 创建服务器
http.createServer((req, res) => {
    // 获取请求路径
    const reqUrl = req.url == '/' ? 'index.html' : req.url;

    fs.readFile(path.join(__dirname, 'www', reqUrl), (err, data) => {
        if (err) {
            // 没有找到对应文件
            res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf8' });
            res.write('404 没有找到资源\n');
            res.write(err.toString());
            res.end();
        }else{
            let contentType = 'text/html';
            // 获取请求文件的后缀
            const ext = path.extname(reqUrl);
            // 根据后缀设置不同的content-type
            if(mime[ext]){
                contentType = mime[ext];
            }
            // 如果是获取文本,需要单独添加utf8的编码格式
            if(ext === '.txt'){
                contentType += '; charset=utf8'
            }
            // 设置响应头
            res.writeHead(200, { 'Content-Tyep': contentType});
            // 返回数据
            res.end(data);
        }
    });
}).listen(8888, '192.168.1.101', () => {    // 绑定ip地址
    console.log('server http://192.168.1.101:8888 is running...');
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

# 静态资源服务器封装

/**
 * 静态资源服务器的封装
 */
const fs = require('fs');
const path = require('path');
const mime = require('./util/mime.json');

exports.staticServer = function (req, res, root) {
    // 获取请求路径
    const reqUrl = req.url == '/' ? 'index.html' : req.url;

    fs.readFile(path.join(root, reqUrl), (err, data) => {
        if (err) {
            // 没有找到对应文件
            res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf8' });
            res.write('404 没有找到资源\n');
            res.write(err.toString());
            res.end();
        } else {
            let contentType = 'text/html';
            // 获取请求文件的后缀
            const ext = path.extname(reqUrl);
            // 根据后缀设置不同的content-type
            if (mime[ext]) {
                contentType = mime[ext];
            }
            // 如果是获取文本,需要单独添加utf8的编码格式
            if (ext === '.txt') {
                contentType += '; charset=utf8'
            }
            // 设置响应头
            res.writeHead(200, { 'Content-Tyep': contentType });
            // 返回数据
            res.end(data);
        }
    });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  • 使用方法:
const http = require('http');
const path = require('path');
const ss = require('./11-静态资源服务器的封装.js');

// 创建服务器
http.createServer((req, res) => {
    ss.staticServer(req, res, path.join(__dirname, 'www'));
}).listen(8888, '192.168.1.101', () => {    // 绑定ip地址
    console.log('server http://192.168.1.101:8888 is running...');
});

1
2
3
4
5
6
7
8
9
10
11
上次更新: 2020/12/06, 21:12:00
nodejs文件操作
解决百度无法收录搭建在GitHub上的个人博客的问题

← nodejs文件操作 解决百度无法收录搭建在GitHub上的个人博客的问题→

最近更新
01
第十章:排序
11-05
02
第九章:查找
11-05
03
第八章:图
11-05
更多文章>
Theme by Vdoing | Copyright © 2020-2021 Liang2uv | 桂ICP备19012079号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式