首先,经典报错:No ‘Access-Control-Allow-Origin’
解决方法:
一、配置main.js
此处已经默认请求都添加/api为前缀
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import 'font-awesome/css/font-awesome.min.css'
Vue.config.productionTip = false
axios.defaults.baseURL='/api/'
Vue.prototype.$axios = axios
new Vue({
router,
render: h => h(App)
}).$mount('#app')
二、配置config.index.js
也就是在proxyTable中写上目标地址,主要是已经重写过/api了,之后的axios请求中都不需要再添加/api,也就是
pathRewrite: {
"^/api":''
}
不需要写作下面这样, 会重复导致报错。
pathRewrite: {
"^/api":“/api”
}
正确的index.js代码:
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: { // 配置代理,下面是个例子
'/api': {
target: 'http://localhost:8880',
changeOrigin: true,
ws:true,
pathRewrite: {
"^/api":''
}
}
},
// host: 'localhost', // can be overwritten by process.env.HOST
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 3000, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false,
useEslint: true,
showEslintErrorsInOverlay: false,
devtool: 'cheap-module-eval-source-map',
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: '/',
assetsPublicPath: './', // 生产环境打包后静态文件路径修改为相对路径
/**
* Source Maps
*/
// productionSourceMap: true,
productionSourceMap: process.env.env_config !== 'prod', // 生产环境不需要sourceMap,测试阶段可为true
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report || true
}
}
三、写请求:get请求为例
axios.get('/student',{//你想访问的资源
params:{
name:"邹xx"//因为后端使用findbyname函数
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});