VUE——axios跨域请求解决及post请求设置为FormData传参
一、axios跨域请求解决
参考地址:https://blog.csdn.net/srttina/article/details/83309
自己最终配置成功代码如下:
1、下载axios依赖,在main.js中引入,添加公共引用接口地址Host
npm i axios --save
import Vue from 'vue' import App from './App' import router from './router' import Vuex from 'vuex' import store from './store' //导入axios import Axios from "axios" //将axios挂载到原型 Vue.prototype.axios = Axios Vue.prototype.Host = '/syrjia' Vue.use(Vuex) Vue.config.productionTip = false
2、config/index.js配置proxyTable
module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/syrjia': {// 这里是公共部分,在调用接口时后面接不相同的部分,/api就相当于http://192.168.0.199:8926/api这一段 target: 'http://localhost:8081/',//这里写的是访问接口的域名和端口号 http://localhost:8081/ changeOrigin: true,// 必须加上这个才能跨域请求 pathRewrite: { // 重命名 '/syrjia': '/syrjia' } } }, // Various Dev Server settings host: '0.0.0.0', // can be overwritten by process.env.HOST port: 8080, // 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- devtool: 'cheap-module-eval-source-map', cacheBusting: true, cssSourceMap: true }, }
3、请求数据
mounted () {
//要以字符串拼接方式传参并且请求头设置成:{headers: {'Content-Type': 'application/x-www-form-urlencoded'}} let parmas='page='+1+'&row='+10+'&memberId=775745745747&channelId=jianyi' this.axios.post(this.Host+'/doctor/queryDoctorListUp.action', //vue post请求设置为FormData传参,如果直接以属性:值的格式传,会报错 parmas, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}} ) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }
是我吖~