vue中axios的get、post请求(代理ProxyTable有效)

get请求一般是没什么的,post请求涉及到代理处理跨域的问题。

不使用代理:

        main.js

                const base = process.env.API_ROOT

                const instance = axios.create({   baseURL:base   })

                Vue.prototype.$http = instance

       使用的位置:

            this.$http({

                    method: 'post',

                    // baseURL: this.HOST,  在main.js已经设置好了

                    url: '/commonCompare/user/login',

                    params: params,  //次数使用params代替data

                    xhrFields: {  withCredentials: true    },  //此处为我的项目与后台跨域配合的处理

                    header: {        ContentType: 'application/json'    }  //数据类型为json,根据实际需求

                }).then((res) => { console.log(res); }).catch((err) => { console.log(err); })

使用代理:

(使用代理关键有一点,配置完了之后要重新npm run dev才能看到效果)

      main.js: 

            Vue.prototype.HOST = '/api'

            Vue.prototype.$http = axios

        config下的index.js的module.exports下的env对象


            使用的位置:

    this.$http.post(this.HOST + '/commonCompare/user/login',params).then((res) => { c

    onsole.log(res); }).catch((err) => { console.log(err); })

或者:

    this.$http({

                    method: 'post',

                    baseURL: this.HOST,  // 在main.js无设置

                    url: '/commonCompare/user/login',

                    params: params,  //次数使用params代替data

                    xhrFields: {  withCredentials: true    },  //此处为我的项目与后台跨域配合的处理

                    header: {        ContentType: 'application/json'    }  //数据类型为json,根据实际需求

}).then((res) => { console.log(res); }).catch((err) => { console.log(err); })

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容