Vue跨域方式

**

1.axios

**
1.在cmd窗口输入以下命令安装到项目目录
cd 项目目录
cnpm install axios -S

2.在项目的main.js中挂载

import axios from 'axios'
Vue.prototype.$http=axios;
//过载axios到vue的原型公共方法上
//所有的vue的实例都将拥有$http

3.get方式
get方式

this.$http.get(url?page=1)
this.$http.get(url,params:{page:2})  //params传参

4.post方式

this.$http.post(url,"k=v&k2=v2",{
	"Content-Type":"application/x-www.form-urlencoded"
})

4.file上传文件

<template>
	<div>
	<input type="file" ref ="file">
</div>
</template>
<script>
	export default {
	let file = this.$refs.file[0]; 
	let data = new FormData().append("file",file);
	 let configs = {
         headers:{'Content-Type':'multipart/form-data'}
      }
      this.$http({
        method:'post',
        url:'/ajax/file.php',
        data,
        configs
      })
}		
</script>

5.全局配置
在mane.js中

axios.defaults.baseURL = "http://xxx.com";
// 配置基础url
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 配置post编码
// axios.defaults.withCredentials = true;
//跨域请求的全局凭证

全局配置完后

$http.get("htttp://www.xxx.com/list.php")
$http.get("/list.php")
效果一样

jsonp跨域

1.在需要使用的组件中导入jsonp

import jsonp from '../assets/js/jsonp'

2.使用
jsonp(“url”,{},
(err,data)=>{
…;
}
)

代理方式跨域

在项目根目录下创建vue.config.js,内容如下

扫描二维码关注公众号,回复: 10835879 查看本文章
module.exports = {
    devServer: {
        open: true, //浏览器自动打开页面
        host: "localhost", //本地服务器访问的路径
        port: 8080, //本地服务器访问的端口
        proxy: {
            '/BtCApi': {
                //你要跨域的域名(包含host、端口号,切记:一定要带上http头);
                //同一个域名只能设置一次跨域,否则重复报错!
                target: 'http://m.gjw.com',  //你要跨域的域名
                changeOrigin: true, //是否跨域,设置为true;(必须)
            },
            // 当用户去访问 http://localhost:8080/feiyan/xxx的时候
            // 咱们的本地服务器器就会去访问 https://iflow-api.uc.cn/feiyan/xxx
            // 让把拿到的数据返回给用户(ajax请求)
            //  这种方法让我们能在开发环境请求下,跨域访问数据。
        }
    },

    publicPath: './'
}
发布了28 篇原创文章 · 获赞 4 · 访问量 628

猜你喜欢

转载自blog.csdn.net/cyang233/article/details/104982004