node原生
通過vscode Live Server將本地檔案在一個服務上開啟,通過本地傳送ajax到node,由於瀏覽器有跨域限制,所以後臺用CORS做了跨域
ajax 程式碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="/1.css">
</head>
<body>
<script>
let xhr = new XMLHttpRequest();
xhr.open('PUT','http://localhost:3000/userList',true);
xhr.responseType = 'json';
xhr.setRequestHeader('token','asd.askfs.g')
xhr.onreadystatechange = function(){
if(xhr.status === 200 && xhr.readyState === 4){
console.log( xhr.response);
}
}
xhr.send();
</script>
</body>
</html>
複製程式碼
node 程式碼如下:
node伺服器程式碼做了簡單的封裝
let http = require('http');
let querystring = require('querystring');
let url = require('url');
let fs = require('mz/fs');
let path = require('path');
let mime = require('mime'); // 第三方模組
class Server{
async handleRequest(req,res){
let {pathname} = url.parse(req.url,true);
let absPath = path.join(__dirname,pathname);
console.log(absPath)
// 先判斷是否是用呼叫的介面 /user get / post /delete / put
let method = req.method.toLowerCase();
// http 無狀態的 cookie xss攻擊
res.setHeader('Access-Control-Allow-Origin','http://localhost:5500');
// 允許的請求方法
res.setHeader('Access-Control-Allow-Methods','GET,PUT,DELETE,OPTIONS,POST');
// 允許的跨域頭
res.setHeader('Access-Control-Allow-Headers','Content-Type,token');
// options的傳送間隔
res.setHeader('Access-Control-Max-age',10);
// 允許前端訪問 攜帶cookie
res.setHeader('Access-Control-Allow-Credentials',true);
if(method === 'options'){ // options不進行處理
res.end(); // 可以訪問我
}
// console.log(req.headers);
switch(pathname){
case '/userList':
if(method === 'get'){
res.setHeader('Content-Type','application/json')
res.end(JSON.stringify({name:'zf'}));
console.log(444)
}
if(method === 'put'){
res.setHeader('Content-Type','application/json')
res.end(JSON.stringify({name:'zf'}));
}
return;
}
//先判斷是不是介面
//
try{
let statObj = await fs.stat(absPath);
//判斷是不是目錄
if(statObj.isDirectory()){
// localhost:3000/a /a/index.html
let realPath = path.join(absPath,'index.html');
await fs.access(realPath);
// 如果訪問的是localhost:3000/a 則realPath =E:\珠峰架構\2019_architecture_course\8.http\a
this.sendFile(realPath,res);
console.log(1)
}else{
//如果訪問的是檔案
// localhost:3000/1.html 1.html
console.log(2)
this.sendFile(absPath,res);
}
}catch(e){ // 捕獲異常
console.log(e);
this.sendError(res,e);
}
}
sendFile(absPath,res){ // 傳送檔案
res.setHeader('Content-Type',mime.getType(absPath));
fs.createReadStream(absPath).pipe(res);
}
sendError(res,err){ // 傳送錯誤
res.statusCode = 404;
res.end(`Not found`);
}
start(port){
let server = http.createServer(this.handleRequest.bind(this));
server.listen(port);
}
}
let server = new Server();
server.start(3000);
複製程式碼