echarts的学习(八)项目服务器端的准备

项目搭建

在这里插入图片描述
在这里插入图片描述

总耗时中间件的开发

在这里插入图片描述

// 计算服务器消耗时长的中间件
//因为要导入这个中间件让其他的地方用,所以用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数据就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一写代码就开心

你的打赏将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值