在app.js中添加app.use(express.static('public'))
http://localhost:3000/index.txt,
访问docx,ppt,excel等文件会自动下载
访问html,txt,png等会在浏览器中打开
访问mp4只会转成mp3,无法播放
可访问静态资源文件
后端的文件模板可以放在public文件夹下,直接访问
在app.js中添加app.use(express.urlencoded({ extended: true }))
可以解析请求体中的form表单数据
在app.js中添加app.use(express.json())
可以解析请求体中的json数据
在引用的时候使用js需要添加.js声明,不然识别不到,ts不需要
import {
addPost,
getPost
} from './post.service.js';
在controller中使用service时候函数不能加括号
post.post('/add', addPost);
安装vscode插件 REST Client
在单独的文件夹里创建一个index.http/demo.http文件,可以像postman一样发送请求
POST http://localhost:3000/post/add HTTP/1.1
Content-Type: application/json
{
"title": "hello",
"content": "world"
}
在express中,每个模块(controller,service,model....)要在app.js中引入
然后添加app.use('/post', post) / app.use('/user', user)
这样就可以在controller中访问到路由了,然后在controller中分不同的路由处理不同的请求
http://localhost:3000/post/add
http://localhost:3000/user/get
在controller中调用service层,service层调用model层
在service层中,使用async await处理异步操作
在model层中,使用mongoose操作数据库
在controller层中,使用express框架处理路由
在app.js中,使用express框架启动服务器
在app.js中,使用cors中间件处理跨域请求
在app.js中,使用body-parser中间件处理请求体
在app.js中,使用cookie-parser中间件处理cookie
在app.js中,使用session中间件处理session
在app.js中,使用multer中间件处理文件上传
跨域
const express = require('express');
const app = express();
const cors = require('cors');
const port = 3000;
const {
Readable
} = require('stream');
// 1、使用cros中间件
const corsOptions = {
origin: 'http://127.0.0.1:5500' // 前端网页或者是服务器地址允许的来源
};
//app.use(cors()); //全部来源支持跨域
app.use(cors(corsOptions)); //白名单支持跨域
// 2、手动设置响应头
// 手动设置响应头来允许跨域请求
const allowedOrigins = ['http://127.0.0.1:5500', 'http://127.0.0.1:3000'];
app.use((req, res, next) => {
// 允许所有来源的跨域请求
const origin = req.headers.origin;
if (origin && allowedOriginRegex.test(origin)) {
// 如果请求的来源匹配正则表达式,则设置响应头允许该来源访问
res.setHeader('Access-Control-Allow-Origin', origin); //白名单支持跨域
}
// res.setHeader('Access-Control-Allow-Origin', '*'); //全部来源支持跨域
// 允许的请求方法
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// 允许的请求头
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// 允许携带凭证(如 cookies)
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
// 假设我们有一个函数可以生成大量数据
function* generateData() {
for (let i = 0; i < 100; i++) {
yield `Data chunk ${i}\n`;
}
}
app.get('/stream', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const dataStream = new Readable({
read() {}
});
const dataGen = generateData();
const sendData = () => {
const {
value,
done
} = dataGen.next();
if (done) {
dataStream.push(null);
} else {
dataStream.push(`data: ${value}\n\n`);
setTimeout(sendData, 200);
}
};
sendData();
dataStream.on('error', (err) => {
console.error('Stream error:', err);
res.status(500).send('Internal Server Error');
});
res.on('error', (err) => {
console.error('Response error:', err);
dataStream.destroy();
});
dataStream.pipe(res);
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});