当前位置: 首页 > 后端技术 > Node.js

模拟数据支持post、put、delete等http方式

时间:2023-04-03 12:31:50 Node.js

一般模拟数据只支持get方法。为了支持post等方式,可以通过将api转给node路由来实现。constexpress=require('express');constapp=express();constapiRouters=express.Router();//模拟数据的地址constpaths=require('./paths');constappMockup=路径。appMockup;apiRouters.all('/column',function(req,res){constfilepath=require.resolve(appMockup+'/column.json');deleterequire.cache[filepath];res.json(require(filepath));});apiRouters.all('/pie',function(req,res){constfilepath=require.resolve(appMockup+'/pie.json');deleterequire.cache[filepath];res.json(require(filepath));});apiRouters.all('/trend',function(req,res){constfilepath=require.resolve(appMockup+'/trend.json');deleterequire.cache[filepath];res.json(require(filepath));});module.exports=apiRouters;//如何使用constexpress=require('express');constapp=express();constapiRouters=require('./mockup');app.使用('/api',apiRouters);注:require函数及其辅助方法主要有:require():加载外部模块rrequire.resolve():将模块名解析为绝对路径require.main:指向主模块require.cache:指向所有缓存的模块require.extensions:根据文件扩展名调用不同的执行函数