VUE - proxy+nodejs解决跨域

2020-08-12  本文已影响0人  coderfl

`
// vue.config.js
const proxy = require('./api/proxy');
module.exports = {
devServer:{
proxy,
port: 3330
}
}

// api/proxy.js
const dev = {dataIp: 'http://10.1.28.216:8090', fileIp: 'http://10.1.28.216:8090'}
const test = {dataIp: '', fileIp: ''}
const pre = {dataIp: '', fileIp: ''}
const prod = {dataIp: '', fileIp: ''}
const baseIp = {
...dev //开发环境
// ...test //测试环境
// ...pre //预发布环境
// ...prod //正式环境
}
const dip = baseIp.dataIp
const fip = baseIp.fileIp
module.exports = {
'/life-medical-medical': {target: dip},
'/V1.0.0/static/inquiry': {target: dip + "/life-mall-visit"},
}

// server.js
//pm2启动项目配置
const fs = require('fs')
const express = require('express')
const app = express();
app.use(express.static('./dist'))
//解决history路由问题
app.get('*', function(req, res) {
const html = fs.readFileSync('./dist/index.html', 'utf-8')
res.send(html)
})
//跨域代理配置
const {createProxyMiddleware} = require("http-proxy-middleware")
const proxy = require('./api/proxy')
Object.keys(proxy).map(value => {
app.use(createProxyMiddleware(value, proxy[value]))
})
//监听端口
app.listen(3300, error => error ? console.log(error) : console.log('start success!'))
`

上一篇下一篇

猜你喜欢

热点阅读