第十周学习笔记和总结

2018-07-29  本文已影响0人  水水壶

这周主要接触了一下 Node。

一、 Node 服务器

const http = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');

const server = http.createServer(function (req, res) {
    if (req.url === '/favicon.ico') {
        return;
    }

    // 请求静态资源
    if (req.url !== '/') {
        let pathname = url.parse(req.url).pathname;
        const extname = path.extname(pathname);
        fs.readFile('.' + pathname, function (err, data) {
            if (err) {
                res.writeHead(404, {'Content-type': 'text/html;charset=UTF-8'});
                res.end('404: Resource Not Found.');
            }
            getmime(extname, function (mime) {
                res.writeHead(200, {'Content-type': mime});
                res.end(data);
            });
        });
    }

    // 首页
    if (req.url === '/') {
        res.writeHead(200, {'Content-type': 'text/html;charset=UTF-8'});
        res.write('<image src="/uploads/1.jpg" alt="照片"></image>');
        res.end();
    }

});

/*获取文件类型*/
function getmime (extname, callback) {
    fs.readFile('./config/mime.json', function (err, data) {
        if (err) {
            return console.log('未找到 mime.json 文件');
        }
        callback(JSON.parse(data)[extname]);
    })
}

server.listen(3000, function () {
    console.log('server is starting on port: 3000.');
});

node 作为 web 服务端,启动后会监听一个端口,一般是默认是port:80,在 web 客户端发送请求,Node 能够接受请求,并作出响应。

1. Node 服务器可以返回哪些资源

如果 html 里有这三个标签,会分别再发一次请求。

2.Node 服务器如何接受客户端传来的信息

二、 git 远程仓库

注册 github 帐号:https://github.com/dreamlin517

注册 gitee 帐号 : https://gitee.com/ydreamlin/events

上一篇 下一篇

猜你喜欢

热点阅读