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

vue+node(express)用于中间层开发

时间:2023-04-03 15:25:57 Node.js

前提安装:vuev2.9.6vue-cliiviewnodev15.4expressv4.16.1axiosv0.18.0cors采用前端vue工程的结构,包含一个节点服务vueendvueinitwebpackvueapp//新建一个vueapp项目,使用默认配置执行npmrundevstartvue$npmrundev>vueapp@1.0.0dev/Users/mac/dongzhiqin/vueapp>webpack-dev-server--inline--progress--configbuild/webpack.dev.conf.js13%buildingmodules32/37modules5active...ers/mac/dongzhiqin/vueapp/src/App.vue{parser:"babylon"}已弃用;我们现在将其视为{parser:"babel"}。95%emittingiDONE在4924ms6:48:54PMI你的应用程序正在运行:http://localhost:8080Introduceiviewandaxiosinmain在.js文件中编辑importaxiosfrom'axios'importViewUIfrom'view-design'import'view-design/dist/styles/iview.css'Vue.prototype.$axios=axios//将axios注册为原型属性Vue.use(ViewUI)edithelloworld.vuefile此时使用了iview组件按钮,设置了两种数据调用方式。界面如下图所示。在node端安装npminstall-gexpress-generator@4,在vueapp下新建server文件夹,切换到server文件夹,执行expressnode_api&&cdnode_api会新建一个node_api项目,然后安装依赖npminstall执行npmstart启动express$npmstart>node-api@0.0.0start/Users/mac/donzhiqin/vueapp/server/node_api>node./bin/www在页面server/node_api/routes/index配置routevar。jsexpress=require('express');varrouter=express.Router();/*获取主页。*/router.get('/',function(req,res,next){res.render('index',{title:'Express'});});router.get('/hi',function(req,res,next){req.name='kim';next();})router.get('/hi',function(req,res){res.send(`hello${req.name}`)})router.get('/request',function(req,res,next){res.send(req.query)})router.post('/postrequest',function(req,res,next){res.send(req.body)})router.get('/user',function(req,res,next){console.log('req:',req)res.send({name:'kim',address:'广州市海珠区',})})module.exports=router;使用浏览器或者postman访问localhost:3000(默认端口3000),可以看到有回车installnodemon实现nodejs热启动npminstall--save-devnodemon,使用nodemon命令提节点命令安装cross-env实现环境变量设置npminstall--save-devcross-env,编辑server/node_api/package.json:{"name":"node-api","version":"0.0.0","private":true,"scripts":{"start:dev":"cross-envNODE_ENV=developmentnodemon./bin/www","start:prod":"cross-envNODE_ENV=productionnode./bin/www"},"dependencies":{"cookie-parser":"~1.4.4","cors":"^2.8.5","debug":"~2.6.9","express":"~4.16.1","http-errors":"~1.6.3","jade":"~1.11.0","morgan":"~1.9.1"},"devDependencies":{"cross-env":"^7.0.3","nodemon":"^2.0.6"}}解决crossdomain这时候前端显示可用,后端数据可用,需要解决跨域问题,因为一个端口是8080,另一个是3000在express的app.js文件中编辑://跨域问题解决constcors=require('cors');app.use(cors({origin:['http://localhost:8080'],methods:['GET','POST'],}));//解决跨域问题app.all('*',function(req,res,next){res.header('Access-Control-Allow-Origin','http://localhost:8080');res.header('Access-Control-Allow-Headers','Content-Type');res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS'); next(); });设置vue的代理,编辑config/index.js:proxyTable:{'/api':{target:'http://localhost:3000/',ChangeOrigin:true,pathRewrite:{'^/api':''}}},重启express,点击界面上的按钮,可以看到服务端发回的数据。接下来可以做什么使用express实现接口转发的功能,将express中间层分离,在server端使用axios,与前端统一