# node常用

# __dirname path.resolve

let http=require("http")
let fs= require("fs")
let app = http.createServer((req,res)=>{
	
	const {method,url,headers}=req;
	res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:8848');
	if(method==="GET"&url==="/favicon.ico"){
		res.end()
	}else if(method==="GET"&url==="/"){
		fs.readFile("index.html",(err,data)=>{
			if(err){
				res.writeHead(500, { 'Content-Type':'text/plain;charset=utf-8' });
			}else{
				// res.statusCode = 200;
				// res.setHeader('Content-Type', 'text/html');
				res.writeHead(200, { 'Content-Type':'text/html;charset=utf-8' });
				res.end(data)
			}
			
		})
		
	}else if(method==="GET"&url==="/json"){
		const json =[{name:"zhangsan",age:18,job:"student"},{name:"lisi",age:28,job:"teacher"}]
		
		res.writeHead(200, {
			
			'Content-Type': 'application/json'
		});
		
		res.end(JSON.stringify(json));
	}else if(method==="GET"&url==="/text"){
		console.log('cookie',req.headers.cookie)
		res.setHeader('Access-Control-Allow-Credentials', 'true');
		res.setHeader('Set-Cookie',"userId=828; userName=hulk; expire=44;");
		  res.writeHead(200, {
		    // 'Set-Cookie': 'myCookie=test',
		    'Content-Type': 'text/plain'
		});
		
		
		const json =[{name:"text",age:18,job:"student"},{name:"text1",age:28,job:"teacher"}]
		
	
		
		res.end(JSON.stringify(json));
	}
	else if(method==="OPTIONS"){
		res.setHeader('Access-Control-Allow-Credentials', 'true');
		res.writeHead(200, {
			"Access-Control-Allow-Origin": "http://127.0.0.1:8848",
			"Access-Control-Allow-Headers": "Authorization,Content-Type",
			"Access-Control-Allow-Methods": "PUT",
			// "Access-Control-Max-Age":30
			});
		res.end();
	}else if (method === 'GET' && headers.accept.indexOf('image/*') !== -1) {
		fs.createReadStream('.'+url).pipe(res);
	}else{
		res.statusCode = 404;
		res.setHeader('Content-Type', 'text/plain;charset=utf-8');
		res.end('404, 页面没有找到');
	}	
	

})
app.listen(9000,()=>{
	console.log("server is ok")
})



<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
		<style>
			#k1{
				width:200px;
				height:200px;
				-webkit-box-shadow: inset 0px 1px 1px -1px rgba(0, 0, 0, 0.5);
			}
			.apple{
				width:100px;
				display:block;
			}
			#btn{
				cursor:pointer
			}
		</style>
	</head>
	<body>
		<div id="k1" class="t1">cccc</div>
		<div class="add"></div>
		<img src="apple.jpg" alt="apple" class="apple">
		<a href="/json">跳转</a>
		<div id="btn">前端界面增加内容</div>
		<div id="btn1">前端界面增加内容1</div>
	</body>
</html>
<script type="text/javascript">
	function ajax(url){
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() 
					: ActiveXObject("microsoft.XMLHttp")
		
        xhr.open("get",url,true);
		xhr.withCredentials = true;
		xhr.setRequestHeader("Authorization",1111)
        xhr.send();
		
        xhr.onreadystatechange= () =>{
			
            if(xhr.readyState == 4){
				
                if(xhr.status == 200){
					console.log(xhr)
                    var data =JSON.parse(xhr.responseText) ;
					let add=document.getElementsByClassName("add")[0];
					let ul=document.createElement("ul");
					
					for(let i in data){
						let li=document.createElement("li")
						console.log(data[i])
						li.innerHTML=JSON.stringify(data[i]) ;
						ul.appendChild(li)
						
					}
					add.appendChild(ul)
					
                    
                }
            }
        }    
    }
	let btn=document.getElementById("btn")
	let btn1=document.getElementById("btn1")
	btn.onclick= ()=>{
		ajax("http://localhost:9000/json")
	}
	btn1.onclick= ()=>{
		ajax("http://localhost:9000/text")
	}

</script>

提示

Accept代表发送端(客户端)希望接受的数据类型。 比如:Accept:text/xml; 代表客户端希望 接受的数据类型是xml类型。 Content-Type代表发送端(客户端|服务器)发送的实体数据的数据类型。 比如:Content- Type:text/html; 代表发送端发送的数据格式是html。 二者合起来, Accept:text/xml; Content-Type:text/html ,即代表希望接受的数据类型是xml格 式,本次请求发送的数据的数据格式是html。

# node跨域写法

if(method==="GET"&url==="/json"){
		const json =[{name:"zhangsan",age:18,job:"student"},{name:"lisi",age:28,job:"teacher"}]
		res.writeHead(200, {
			"Access-Control-Allow-Origin": "http://127.0.0.1:8848",
			'Content-Type': 'application/json'
		});
		res.end(JSON.stringify(json));
}

如果是前后端分离的模式,则cookie前后端都要开启Credentials!!!

对于上方的indexhtml可以在后台9000打开,也可以前后端分离使用8848端口打开体验

# 文件预览后端提供

const http = require('http');
const fs = require('fs'); // 使用 fs 而不是 fs.promises
const path = require('path');

// 服务器根目录
const rootDir = path.join(__dirname, 'files');

// 允许所有源访问(出于安全考虑,通常不建议在生产环境中这样做)
const allowedOrigins = '*'; // 或者指定具体的域名,如 'http://example.com'

// MIME 类型映射
const mimeTypeMap = {
  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  '.md': 'text/markdown',
  '.jsx': 'application/javascript', // 或者 'text/jsx' 根据你的需求
  '.pdf': 'application/pdf',
  '.png': 'image/png',
  '.gif': 'image/gif',
  '.txt': 'text/plain',
  // 你可以在这里继续添加更多的MIME类型映射
};

// 创建HTTP服务器
const server = http.createServer((req, res) => {
  // 立即设置CORS响应头
  if (req.headers.origin) {
    res.setHeader('Access-Control-Allow-Origin', allowedOrigins);
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    // 如果请求方法是OPTIONS(预检请求),则直接返回204状态码
    if (req.method === 'OPTIONS') {
      res.statusCode = 204;
      return res.end();
    }
  }

  // 解析请求的URL路径,并去除开头的斜杠
  const requestedPath = req.url.replace(/^\/?/, '');
  const filePath = path.join(rootDir, requestedPath);

  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      // 文件不存在,返回404错误
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('File not found');
      return;
    }

    fs.stat(filePath, (err, stats) => {
      if (err || !stats.isFile()) {
        // 如果获取文件信息出错,或者不是一个文件,返回403错误
        res.writeHead(403, { 'Content-Type': 'text/plain' });
        res.end('Access denied or not a file');
        return;
      }

      // 设置响应头
      const ext = path.extname(filePath).toLowerCase();
      let contentType = mimeTypeMap[ext] || 'application/octet-stream'; // 使用映射或默认类型

      res.writeHead(200, {
        'Content-Type': contentType,
        'Content-Length': stats.size,
        'Content-Disposition': `attachment; filename="${path.basename(filePath)}"`,
        // 重复设置CORS响应头(虽然在这里不是必需的,因为已经在开始时设置了)
        'Access-Control-Allow-Origin': allowedOrigins,
      });

      // 创建可读流来读取文件内容
      const fileStream = fs.createReadStream(filePath);

      // 将文件流管道到响应对象
      fileStream.pipe(res);

      // 监听错误事件
      fileStream.on('error', (err) => {
        console.error('File stream error:', err);
        // 注意:如果文件流出错,连接可能已经关闭,这里向客户端发送错误响应可能无效。
        // 在实际应用中,你可能需要记录错误并采取其他措施。
      });
    });
  });
});

// 服务器监听端口
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server is running at http://localhost:${PORT}`);
});
最后更新: 1/16/2025, 10:15:46 PM