项目搭建
总耗时中间件的开发
// 计算服务器消耗时长的中间件
//因为要导入这个中间件让其他的地方用,所以用exports导出
//参数 ctx 意思是上下文,next意思是中间件的入口
module.exports = async (ctx, next) => {
// 记录开始时间
const start = Date.now();
// 让内层中间件得到执行
await next();
// 记录结束的时间
const end = Date.now();
// 设置响应头 X-Response-Time
const duration = end - start;
// ctx.set() 设置响应头
ctx.set('X-Response-Time', duration + 'ms')
}
响应头中间件
// 设置响应头的中间件
module.exports = async (ctx, next) => {
const contentType = 'application/json; charset=utf-8';
ctx.set('Content-Type', contentType);
ctx.set("Access-Control-Allow-Origin", "*");
ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
await next()
};
业务逻辑的中间件
// 处理业务逻辑的中间件,读取某个json文件的数据
const path = require('path');
const fileUtils = require('../utils/file_utils');
module.exports = async (ctx, next) => {
// 根据url 也就是前端发过来的url
const url = ctx.request.url; // /api/seller ../data/seller.json
let filePath = url.replace('/api', ''); // /seller 将前端传过来的url进行处理
filePath = '../data' + filePath + '.json'; // ../data/seller.json 获得正式的路径
filePath = path.join(__dirname, filePath); //绝对路径
try {
const ret = await fileUtils.getFileJsonData(filePath);
ctx.response.body = ret
} catch (error) {
const errorMsg = {
message: '读取文件内容失败, 文件资源不存在',
status: 404
};
ctx.response.body = JSON.stringify(errorMsg)
}
console.log(filePath);
await next()
};
启动项目
node app.js
以上就是后端返回的数据
允许跨域
我们就可以在后端设置跨域请求
// 设置响应头的中间件
module.exports = async (ctx, next) => {
const contentType = 'application/json; charset=utf-8';
ctx.set('Content-Type', contentType);
ctx.set("Access-Control-Allow-Origin", "*");
ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
await next()
};
小结
这个项目就是搭建了一个服务端的项目,就是为了给前段返回json数据,其实我们可以使用django项目,springboot项目给前段返回json数据。
总之,后端只要给前段返回json数据就可以了。