0
点赞
收藏
分享

微信扫一扫

vue解决跨域问题(下)

yundejia 2022-07-27 阅读 63


目录

  • ​​1. 前言​​
  • ​​2. 问题引入​​
  • ​​2.1 整合后端问题​​
  • ​​2.2 整合前端问题​​
  • ​​3. 解决方案​​
  • ​​3.1 方案1(无效)​​
  • ​​3.2 方案1错误分析​​
  • ​​3.3 方案2(亲测有效)​​
  • ​​4. 参考文献​​

1. 前言

最近在学习 vue 与 SSM 实现前后端分离,碰到了一些棘手的问题,首先初次接触前后端分离这个概念还不是很清楚,网上的教程也是比较稀缺,所以自己也是花了点时间来理解了下这个概念,然后网上找了一个案例来看看前后端分离的具体效果。但是在这个过程中确实充满了艰辛,下面来看看我的填坑记录。

2. 问题引入

前后端分离,无非就是分别将后端和前端整合好,然后将后端的地址拿给前端,最后开启各自的服务,实现联互通。

2.1 整合后端问题

这里的话,就是以SSM框架为例进行的一个增删改查案例,我们需要做的事情就是在 IDEA 里面整合SSM框架,这里不在描述。

2.2 整合前端问题

前端的话使用的是 ws(webstorm) 编译器进行开发的,然后在上面编写前端效果,这里的主要问题就是跨域问题,首先我要获取来自后端的数据然后展示在前端,这里就出现了很多坑,导致我一直无法跨域成功,下面主要将讲解下自己如何解决这个跨域问题。

3. 解决方案

这里我需要说明的是我编译器使用的是webstorm新建vue项目的,webstorm版本是最新版2021的,使用webstorm新建项目一般是下面这种结构:

vue解决跨域问题(下)_ios

3.1 方案1(无效)

这里我首先在网上搜索的问题是:

vue解决前后端分离跨域问题

然后看到网上给的一个参考文章,说在项目下新建一个config文件夹:

vue解决跨域问题(下)_ios_02


然后在config里面新建一个index.js 在里面写入这些代码:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
devServer: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://127.0.0.1:8080',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
},

// Various Dev Server settings
host: '127.0.0.1', // can be overwritten by process.env.HOST
port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,

/**
* Source Maps
*/

// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',

// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,

cssSourceMap: true
},

build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),

// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',

/**
* Source Maps
*/

productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',

// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],

// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}

这里我截个图说明下:

vue解决跨域问题(下)_跨域问题_03


按照图示定义自己的后端地址,然后我们在main.js写个测试方法:

import Vue from 'vue'
import App from './App.vue'
import router from './router';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import qs from 'qs';
import axios from "axios";
// import request from "@/network/request";


// 阻止显示生产模式的消息
Vue.config.productionTip = false;
//配全局属性配置,在任意组件内可以使用this.$qs获取qs对象
Vue.prototype.qs = qs


// 引用axios,并设置基础URL为后端服务api地址

// axios.defaults.baseURL = "http://127.0.0.1:8080"

// axios.defaults.baseURL = '/api'

// Vue函数添加一个原型属性$axios 指向Axios,这样做的好处是在vue实例或组件中不用再去重复引用Axios 直接用this.$axios就能执行axios 方法了
Vue.prototype.axios = axios;
Vue.use(ElementUI);


// 测试方法
axios.get('/api/user/findAll').
then(res => {
console.log(222222)
console.log(res.data) // 跨域成功显示这句话
}).catch(res =>{
console.log(res.error)
console.log(111111) // 跨域失败
})


new Vue({
router,
render: h => h(App),
}).$mount('#app')

最后出现下面这种错误:

Proxy error: Could not proxy request /user/getRowCount from 127.0.0.1:8081 to 127.0.0.1:8080.

3.2 方案1错误分析

针对这种问题,我也是纠结了很久,查了很多资料,最后还是自己摸索出来了错误原因,因为方案1针对的是 vue CLI2 才那样做的,对于我使用的是vue CLI3 这种方法不适合,所以我试了上面很多种方法都无效,故不管怎么在config/index.js下改都是无用的。

3.3 方案2(亲测有效)

这种方法是针对与vue CLI3 有用,之前我就是用这种方法解决跨域问题的,所以我直接告诉解决方法。首先我们在项目下新建一个vue.config.js如下所示:

vue解决跨域问题(下)_跨域问题_04


然后在里面写配置信息:

// const path = require('path')

module.exports = {
// // 部署应用包时的基本 URL,用法和 webpack 本身的 output.publicPath 一致
// publicPath: './',
// // 输出文件目录
// outputDir: 'dist',
// // eslint-loader 是否在保存的时候检查
// lintOnSave: true,
// // 是否使用包含运行时编译器的 Vue 构建版本
// runtimeCompiler: false,
// // 生产环境是否生成 sourceMap 文件
// productionSourceMap: false,
// // 生成的 HTML 中的 <link rel="stylesheet"> 和 <script> 标签上启用 Subresource Integrity (SRI)
// integrity: false,
// // webpack相关配置
// chainWebpack: (config) => {
// config.resolve.alias
// .set('vue$', 'vue/dist/vue.esm.js')
// .set('@', path.resolve(__dirname, './src'))
// },
// configureWebpack: (config) => {
// if (process.env.NODE_ENV === 'production') {
// // 生产环境
// config.mode = 'production'
// } else {
// // 开发环境
// config.mode = 'development'
// }
// },
// // css相关配置
// css: {
// // 是否分离css(插件ExtractTextPlugin)
// extract: true,
// // 是否开启 CSS source maps
// sourceMap: false,
// // css预设器配置项
// loaderOptions: {},
// // 是否启用 CSS modules for all css / pre-processor files.
// modules: false
// },
// // 是否使用 thread-loader
// parallel: require('os').cpus().length > 1,
// // PWA 插件相关配置
// pwa: {},
// webpack-dev-server 相关配置
devServer: {
open: true,
host: '127.0.0.1',
port: 8081,
https: false,
hotOnly: false,
// http 代理配置
proxy: {
'/api': {
target: "http://127.0.0.1:8080", //目标接口域名
changeOrigin: true, //是否跨域
logLevel: "debug",
pathRewrite: {
'^/api': ''
}
}
},
// before: (app) => {}
},
// // 第三方插件配置
// pluginOptions: {
//
// }
}

最后在main.js里写个测试就可以:

import Vue from 'vue'
import App from './App.vue'
import router from './router';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import qs from 'qs';
import axios from "axios";
// import request from "@/network/request";


// 阻止显示生产模式的消息
Vue.config.productionTip = false;
//配全局属性配置,在任意组件内可以使用this.$qs获取qs对象
Vue.prototype.qs = qs


// 引用axios,并设置基础URL为后端服务api地址

// axios.defaults.baseURL = "http://127.0.0.1:8080"

// axios.defaults.baseURL = '/api'

// Vue函数添加一个原型属性$axios 指向Axios,这样做的好处是在vue实例或组件中不用再去重复引用Axios 直接用this.$axios就能执行axios 方法了
Vue.prototype.axios = axios;
Vue.use(ElementUI);

axios.get('/api/user/findAll').
then(res => {
console.log(222222)
console.log(res.data)
}).catch(res =>{
console.log(res.error)
console.log(111111)
})


new Vue({
router,
render: h => h(App),
}).$mount('#app')

最后完美运行:

vue解决跨域问题(下)_css_05

以上就是自己的解决方法,希望对你有所帮助。

4. 参考文献

​​1. vue解决跨域问题(上)​​


举报

相关推荐

0 条评论