1.node的内置模块 - http
http模块-----服务器模块(后端)
功能:
搭建服务器 完成服务器功能
发起请求(类似ajax) --- 不会产生跨域
node中全面支持es6
const http = require("http");
const serverObj = http.createServer((req, res)=>{
if(req.url !== "/favicon.ico"){
console.log("有人访问了这个服务器")
res.writeHead(200,{"content-type":"text/html;charset=utf-8"})
switch(req.url){
case "/":
res.write("首页");break;
case "/index":
res.write("首页");break;
case "/page":
res.write("分页");break;
case "/news":
res.write("新闻");break;
default:
res.write("404");
}
res.end();
}
});
serverObj.listen("3000","127.0.0.1",()=>{
console.log("服务器开启成功,请访问:http://127.0.0.1:3000")
});
2.node的内置模块 - fs
const fs = require("fs");
const data = fs.readFileSync("./world.txt","utf-8");
console.log(data);
3.http模块和fs模块结合
const http = require("http");
const fs = require("fs");
http.createServer((req, res)=>{
if(req.url !== "/favicon.ico"){
fs.readFile("./www" + req.url, (err, data)=>{
if(!err){
res.write(data);
}else{
res.write("404");
}
res.end();
})
}
}).listen("3000");
4.node的内置模块 - url+querystring(包含ajax)
url详解
const http = require("http")
const fs = require("fs")
const url = require("url")
const qs = require("querystring")
http.createServer((req, res) => {
if (req.url !== "/favicon.ico") {
let urlObj = url.parse(req.url, true)
if (urlObj.pathname === "/api") {
ajax(req, res)
} else {
file(req, res)
}
}
}).listen("3000")
function ajax(req, res) {
let urlObj = url.parse(req.url, true)
let str = "";
req.on("data", (res) => {
str += res;
})
req.on("end", () => {
let dataObj = "";
if (str === "") {
dataObj = urlObj.query
} else {
dataObj = qs.parse(str)
}
console.log(dataObj)
})
}
function file(req, res) {
fs.readFile("./www" + req.url, (err, data) => {
if (err) {
res.write("404")
} else {
res.write(data)
}
res.end();
})
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<h1>首页</h1>
用户名:<input type="text" id="un"><br> 密码:
<textarea name="" id="pw"></textarea><br>
<input type="button" id="btn1" value="get请求-登录">
<input type="button" id="btn2" value="post请求-注册">
</body>
<script src="jquery.js"></script>
<script>
$("#btn1").click(function() {
$.ajax({
url: "http://localhost:3000/api",
type: "get",
data: {
un: $("#un").val(),
pw: $("#pw").val()
},
success: (res) => {
console.log(res)
}
})
})
$("#btn2").click(function() {
$.ajax({
url: "http://localhost:3000/api",
type: "post",
data: {
un: $("#un").val(),
pw: $("#pw").val()
},
success: (res) => {
console.log(res)
}
})
})
</script>
</html>