分为:
```
静态资源:比如:css、js、html等。
Json数据:数据库
发起请求的一方称之为客户端
接受请求然后做出相应的叫服务器 server
在全局下载个 node-dev 的包(浏览器会自动更新 response.write()里的内容)
服务器地址=协议+IP+端口+路径+[参权]
```
* 协议:http(默认)、https、morgodlb
* IP:172.0.1.1
端口:80880
* 路径:/(默认以/开头)
* 参数:?(默认以?开头)
#### 建立服务器:
```
const http = require("http")
http.createServer((request, response) => {
//在客户端发起请求时执行
//console.log(request.url) //客户端给服务器发起的请求路径
//console.log(request.method) //客户端的请求方式
//response.statusCode = 200; //设置响应的状态码,默认200
//设置响应头信息
//response.setHeader("content-Type",
"text/html;charset=UTF-8")
//response.setHeader("content-Length",3)只显示三个字节
//合并
//response.writhHead(404,"content-Type",
"text/html;charset=UTF-8")
response.write("sss11115555vvv5") //设置响应内容只能放字符串 buffer("123")
response.end() //结束响应 只能放字符串 buffer("123") 必须调用
}).listen(8080) //端口号
//回调函数用于处理客户端的请求,并对客户端作出响应
//request 请求
//response 响应
```
* dirname 当前该变量所在的文件的绝对路径
* filname 获取当前执行文件的带有绝对路径的文件名
#### 起服务切换页面
```
const fs = require("fs");
const path = require("path");
http.createServer((req, res) => {
let pathname = ""
if (req.url == "/") {
pathname = path.join(__dirname, "index.html")
console.log(pathname)
} else {
pathname = path.join(__dirname, req.url)
console.log(pathname)
}
res.end(fs.readFileSync(pathname))
}).listen(8080);
````
#### content-Type
```
text/plain 纯文本
text/html、text/css、text/javascript(加载js)image/png(加载图片)
application/json(加载json)
```
-------------
### 起服务
```
1. const http = require("http");
http.createServer((request, response) => {
response.end("ljeasdghfdsfgdsafgdsfvbfdsfvb") //结束协议
}).listen("2222")
2.var http = require('http');
var server = http.createServer(function(req, res) {
res.end('hello word,beijing');
}).listen(9213, function() {
console.log('服务开启, 端口号: 9213');
});
```
### 前后端form方式交互 get方式
```
<!--http不能省略 -->
<!-- form默认是get,如果是需要请d求post,必须要手动改成post -->
<!-- 客户通过post方式传递数据时,数据量大小不受限制,这时,在网络传输过程中,会将数据分段发送,服务器的data的事件就会被触发一次 -->
//form.html页面写的代码
<form action="http://localhost:9999" method="post">
<input type="text" name="user">
<input type="password" name="pae">
<input type="submit" value="提交">
<textarea name="text" id="" cols="30" rows="10"></textarea>
js代码
const { createServer } = require("http");
const { parse } = require("url");
const sever = createServer((req, res) => {
// if (req.url === "/favicon.ico") {
// return res.end()
// }
console.log(req.url)
console.log(parse(req.url, true).query)
res.end("hello beiing ajdsaidb")
}).listen(9090, () => console.log('listen port:' + sever.address().port))
```
### post请求交互以下的事件:on(data)->发送
```
const { createServer } = require("http");
const { parse } = require("url");
const sever = createServer((req, res) => {
if (req.url === "/favicon.ico") {
return res.end()
}
var str = "" //拼接
req.on("data", chunk => { //拼接数据
str += chunk;
// console.log(chunk.toString())
})
req.on("end", () => console.log(parse(str))) //已经拿到完整数据了
console.log(str);
// console.log(req.url) //获取请求体
// console.log(parse(req.url, true).query)
res.end("hello wodek")
}).listen(9999, () => console.log('listen port:' + sever.address().port))
```
### 静态文件
* 主要是讲的服务地址和本地地址路径是否一样,如果不一样就返回自己所设置的页面->404-not-found反之一眼就返回页面
```
const { createServer } = require("http");
const { readFile } = require("fs");
const { join } = require("path");
const { parse } = require("url");
const server = createServer((req, res) => {
if (req.url == "/favicon.ico") {
return res.end()
}
let pathname = parse(req.url).pathname
console.log(pathname)
let filePath = req.url == "/" ? join(__dirname, "index.html") : join(__dirname, req.url)
readFile(filePath, (err, data) => {
if (err) {
return res.end("not found!")
}
res.writeHead(200, { "content-Type": "textml;charset=UTF-8" });
res.write(data.toString())
res.end()
})
}).listen(9999, () => {
console.log("listen.prot:" + server.address().port)
})
```
### [ajax前后端的交互
* 需要写json数据,以及ajax]
* @func [需要背下来ajax]
```
const { createServer } = require("http");
const { readFileSync } = require("fs");
const { join } = require("path");
const { parse } = require("url");
//const json = require("./data.json");
const server = createServer((req, res) => {
if (req.url == "/favicon.ico") { //网络规定必须是加/。
return res.end()
}
//1.让服务器支持跨
//res.setHeader("Access-Control-Allow-Origin", "*")
let data = ""
if (req.url == "/index.html") {
data = readFileSync("./index.html")
} else {
data = readFileSync("./data.json")
}
res.end(data)
}).listen(5555, () => {
console.log("listen.prot:" + server.address().port)
})
```
### 建立服务器代码全
```
const { createServer } = require('http'); //创建服务器
const { parse } = require('url');
const { join, extname } = require('path');
const { readFileSync, existsSync } = require('fs'); //读文件
const { parse: qsParse } = require('querystring');
const data = require('./static/data'); //json地址
console.log(data);
const server = createServer((req, res) => { //搭建服务器
if (req.url === '/favicon.ico') {
return res.end();
}
let { pathname, query } = parse(req.url, true);
pathname = pathname === '/' ? 'index.html' : pathname;
const ext = extname(pathname); //取后缀名
if (ext) { //如果有后缀名
const filename = join(__dirname, 'static', pathname); //规范路径
if (existsSync(filename)) {
res.end(readFileSync(filename))
} else {
res.writeHead(302, { //重定向
'Location': 'error.html'
});
res.end();
}
} else {
if (req.method === 'GET') {
res.end(JSON.stringify(data));
} else if (req.method === 'POST') {
let str = '';
req.on('data', chunk => {
str += chunk;
})
req.on('end', () => {
const contype = req.headers['content-type'];
console.log(contype);
if (contype === 'application/json') {
console.log(JSON.parse(str));
res.end(JSON.stringify(data));
} else {
console.log(qsParse(str));
res.end(JSON.stringify(data));
}
});
} else {
res.end(error);
}
}
}).listen(4433, () => console.log(server.address().port));