这周主要接触了一下 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 超文本
'Content-type': 'text/html;charset=UTF-8'
- 可以返回纯文本
'Content-type': 'text/plain;charset=UTF-8'
- 可以返回图片
'Content-type': 'image/jpeg'
- 返回 json 格式
'Content-type': 'text/json'
如果 html 里有这三个标签,会分别再发一次请求。
<image src="1.jpg"></image>
<script src="index.js"></script>
<link href="style.css">
2.Node 服务器如何接受客户端传来的信息
- params 接受参数,参数写在 url 里 /user/13
- query(询问,用到问号) 参数也是写在 url 里,不过是写在问号后面 /user?name=dkvirus
- post form 表单传值
- 上传操作
二、 git 远程仓库
注册 github 帐号:https://github.com/dreamlin517
注册 gitee 帐号 : https://gitee.com/ydreamlin/events