Vue cross domain method

**

1.axios

**
1. Enter the following command in the cmd window to install to the project directory
cd 项目目录
cnpm install axios -S

2. Mount in the main.js of the project

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

3.
get way get way

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

4.post method

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

4.file upload 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. Global configuration
in 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;
//跨域请求的全局凭证

After global configuration

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

jsonp cross domain

1. Import jsonp in the component you need to use

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

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

Cross-domain proxy

Create vue.config.js in the project root directory, the content is as follows

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: './'
}
Published 28 original articles · praised 4 · visits 628

Guess you like

Origin blog.csdn.net/cyang233/article/details/104982004