feat: 添加服务器相关配置和代码

This commit is contained in:
= 2024-05-04 01:00:42 +08:00
parent 7475dfdaf1
commit 47d42c3482
9 changed files with 1601 additions and 0 deletions

1351
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
package.json Normal file
View File

@ -0,0 +1,22 @@
{
"name": "js-review",
"version": "1.0.0",
"type": "module",
"description": "一个有关前端复习的仓库",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"server": "nodemon ./server/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.15.3",
"koa-body": "^6.0.1",
"koa-router": "^12.0.1"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}

12
server/index.js Normal file
View File

@ -0,0 +1,12 @@
import Koa from 'koa'
import router from './router/index.js'
import logger from './middleeare/logger.js'
const app = new Koa()
app.use(logger())
app.use(router.routes());
app.listen(3001, ()=>{
console.log("服务器开启成功端口为3001");
})

View File

@ -0,0 +1,30 @@
function loggingMiddleware() {
return async (ctx, next) => {
const start = Date.now();
try {
// 打印请求路径、方法和参数
console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} ${JSON.stringify(ctx.request.body)}`);
// 调用下一个中间件
await next();
// 打印请求处理时间
const ms = Date.now() - start;
console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - ${ms}ms`);
// 打印请求是否成功
if (ctx.status >= 400) {
console.error(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Failed (${ctx.status})`);
} else {
console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Success (${ctx.status})`);
}
} catch (error) {
// 打印错误信息
console.error(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Error (${error.message})`);
ctx.status = 500; // 设置状态码为 500
ctx.body = 'Internal Server Error';
}
};
}
export default loggingMiddleware;

12
server/router/index.js Normal file
View File

@ -0,0 +1,12 @@
import Router from 'koa-router'
import upload from './upload.js'
import test from './test.js'
const router = new Router()
// 添加上传相关路由
router.use(upload.routes())
// 添加测试相关路由
router.use(test.routes())
export default router

44
server/router/test.html Normal file
View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传demo</title>
</head>
<body>
<h1>
单文件上传
</h1>
<form>
<label for="single">上传文件</label>
<input type="file" id="sigle">
<button id="senBtn">上传</button>
</form>
<div id="fileResult">
</div>
<script>
let sigle = document.getElementById('sigle')
senBtn.addEventListener('click', ()=>{
// if(!sigle.files.length) {
// alert("请先选择文件")
// return
// }
// let formData = new FormData()
// // formData.append('touxiang', sigle.files[0])
// formData.append('name', '小明')
// fetch("/test/upload", {
// method: 'POST',
// body: formData
// }).then(res=>res.json()).then(data=>{
// fileResult.innerHTML = data.msg
// })
let formData = new FormData()
formData.append('name','下令')
formData.append('age','测试')
]
})
</script>
</body>
</html>

36
server/router/test.js Normal file
View File

@ -0,0 +1,36 @@
import Router from 'koa-router'
import { koaBody } from 'koa-body'
import path from 'path'
import fs from 'fs/promises'
// 创建router实例
const router = new Router({prefix: '/test'})
router.get('/', async ctx=>{
const page = await fs.readFile(path.resolve(import.meta.dirname, 'test.html'), 'utf-8')
ctx.type = 'text/html'
ctx.status = 200
ctx.body = page
})
router.post('/upload', koaBody({multipart: true}), async ctx=>{
try{
console.log(ctx.request.body);
ctx.status = 200
ctx.body = JSON.stringify({msg: '文件上传成功'})
}catch(err){
ctx.status = 403
ctx.type = 'application/json'
ctx.body = JSON.stringify({msg: '上传文件发生错误'})
}
ctx.body = '接收数据成功'
})
router.post('/data', koaBody({multipart: true}), async ctx=>{
console.log(ctx.request.body);
ctx.status = 200
ctx.body = "发送成功"
})
export default router

40
server/router/upload.html Normal file
View File

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>Upload File</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput">
<button type="submit">Upload</button>
</form>
<div id="message"></div>
<script>
document.getElementById('uploadForm').addEventListener('submit', async function(event) {
event.preventDefault();
const formData = new FormData();
const fileInput = document.getElementById('fileInput');
formData.append('file', fileInput.files[0]);
const response = await fetch('/upload/single', {
method: 'POST',
body: formData
});
const messageDiv = document.getElementById('message');
if (response.ok) {
messageDiv.textContent = 'File uploaded successfully';
} else {
const errorMessage = await response.text();
messageDiv.textContent = `Error: ${errorMessage}`;
}
});
</script>
</body>
</html>

54
server/router/upload.js Normal file
View File

@ -0,0 +1,54 @@
import Router from 'koa-router'
import { default as fs, promises as pfs } from 'fs'
import path from 'path'
import {koaBody} from 'koa-body'
const router = new Router({prefix: '/upload'})
router.get('/', async ctx => {
try {
// 读取 HTML 文件的内容
const htmlContent = await pfs.readFile(path.join(import.meta.dirname, 'upload.html'), 'utf8');
// 将 HTML 文件内容作为响应发送
ctx.type = 'text/html';
ctx.body = htmlContent;
} catch (error) {
console.error('Error reading HTML file:', error);
ctx.status = 500;
ctx.body = 'Internal Server Error';
}
})
// 接收上传文件的路由,每次只能上传一个
router.post('/single', koaBody({
multipart: true,
formidable: {
uploadDir: path.join(import.meta.dirname, 'upload', 'image'),
keepExtensions: true, // 保持文件扩展名
maxFileSize: 10 * 1024 * 1024 // 10 MB
}
}), async (ctx, next) => {
try {
const file = ctx.request.files.file; // 获取上传的文件对象
// 获取文件类型
const fileType = file.type.split('/')[1];
// 检查文件类型,这里假设只允许上传 jpg 文件
if (fileType !== 'jpg') {
ctx.status = 415; // 不支持的媒体类型
ctx.body = 'Unsupported file type (only .jpg allowed)';
return;
}
ctx.status = 200;
ctx.body = 'File uploaded successfully';
} catch (error) {
console.error('Error uploading file:', error);
ctx.status = 500;
ctx.body = 'Internal Server Error';
}
});
export default router