为了应对业务的复杂性,提高前端的渲染能力,故在项目中引入nodejs做中间层,前端承接vue,后端对接Java。
至于为什么这么搞,网上有好多文章都在讨论,可以说仁者见仁智者见智,这里我们不在深究。
这里主要记录一下,我在项目中尝试使用这种结构遇到的问题:
1.前端的vue工程采用axios请求中间层node服务会遇到跨域问题
解决方法:打开vue工程的index.js配置文件添加如下配置
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {'/api': {target: 'http://localhost:3000',changeOrigin: true,pathRewrite: {'^/api': ''}}
},
2.中间层使用axios请求后端接口时需要等待接口返回后,在传递数据给前端,这里就需要使用同步请求机制
解决方法:采用 async, await 方式,如下
var express = require('express')
var router = express.Router()
var http = require('../config/http')router.get('/getFarmTargets', async (req, res, next) => {console.log('进入请求')var result = {}result.targets = await http.get('/cim/cimInfos/survey?orgId=1115').then(response => response.data.code === 0 ? response.data.data : null)result.introductions = await http.get('/cim/introductions', { orgId: 1115 }).then(response => response.data.code === 0 ? response.data.data : null)console.log('回调外层2:' + JSON.stringify(result))res.json({code: '0',msg: '',data: result})next()
})
先记录到这儿,未完待续......