学习连接 - 重要❤ - 一文详解vue-cli2.0与vue-cli3.0之间的区别
1. vue cli 2.0项目
2. 本地运行时,不同端口号,前后端项目数据互通 通过proxyTable,所以只在index.js 里面的 dev配置了
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
API_ROOT: '"http://192.168.2.121:8088/api"'
})
'use strict'
module.exports = {
NODE_ENV: '"production"',
API_ROOT: '"https://www.***.com/api"' // https://线上域名/api
}
'use strict'
const path = require('path')
//const url = 'https://线上域名/api/'; //正式接口服务器路径
const url = 'http://127.0.0.1:8002'; //本地访问后端路径
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: url,
changeOrigin: true, // 跨域
pathRewrite: {
'^/api': '/' //把路径里面的api去掉
}
}
},
// Various Dev Server settings
host: '192.168.2.121', // can be overwritten by process.env.HOST
port: 8088, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
... ...
}
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
... ...
}
//新建 axios 实例 -- https://www.axios-http.cn/docs/intro
const request = axios.create({
baseURL: process.env.API_ROOT, //前端路径,会通过 index.js 的 proxyTable 跨域处理
timeout: 100000, //请求超时
withCredentials: true, // 跨域请求,允许保存cookie
})
... ...
import request from "./request";
export function getCaptcha (){
return request({
url: '/captcha',
method: 'get',
responseType: 'arraybuffer'
})
}
本地访问页面:http://127.0.0.1:8088/index
后端访问接口:http://127.0.0.1:8002/captcha
直接从前端访问后端,数据不通,通过proxyTable进行跨域配置
'/api': {
target: url,
这个含义就是 用 ' /api ' 区分访问 页面 还是 接口数据
http://127.0.0.1:8088/api ====就是访问target====> http://127.0.0.1:8002/api
proxyTable: {
'/api': {
target: url,
changeOrigin: true, // 跨域,重要
pathRewrite: {
'^/api': '/' //把路径里面的api去掉
}
}
pathRewrite 作用路径重写,因为后端接口路劲没有 ' /api ' 这个字符串
http://127.0.0.1:8088/api/captcha
====就是访问target====> http://127.0.0.1:8002/api/captcha
====通过pathRewrite====> http://127.0.0.1:8002/captcha