vue-cli教程(五) 网络请求与跨域问题解决

网络请求采用jquery,Axios  vue-resource都可以,这里采用vue-resource

安装:cnpm install vue-resource

建立server/index.js

import Vue from 'vue'
import vueresource from 'vue-resource'
Vue.use(vueresource);
//以form的形式提交post,如果不加这个参数,在php端需要以 file_get_contents("php://input")获取参数
Vue.http.options.emulateJSON = true;
const net = {
    BASE_PATH:"/api",
    get_data:function (params) {
        return Vue.http.get(this.BASE_PATH+"/b.php")
    }
};
export default net;

在模板使用:

<template>
    <div>
        <button v-on:click="get_data()">点我获取内容</button>
    </div>
</template>

<script>
import Net from '../server/index'
export default {
    name:"net",
    methods:{
        get_data:function () {
            const res = Net.get_data(1233);
            res.then(function (data) {
                    console.log(data.data)
                },function (e) {
                    console.log(e)
                }
            )
            res.catch(function (e) {
                console.log("from catch",arguments)
            })
        }
    }
}

</script>

此时点击获取时,会出现跨域问题:(js报错)

XMLHttpRequest cannot load http://localhost/api/b.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.

调试的解决方案:

    在config/index.js 下配置 30 行的 proxyTable

proxyTable: {
    //可配置多个规则
    '/api': {
        target: 'http://localhost',  //服务器端地址
        changeOrigin:true,           //忽略请求的origin
        pathRewrite: {
            '^/api': '/test/api'     //url重写规则,可以配置多个
        }
    }
},

    配置成功后重启 才会生效 !!!!!!

在服务器端的解决方案:

     配置nginx反向代理,或者打包后和后端服务器代码放一起

猜你喜欢

转载自my.oschina.net/u/2528821/blog/1555505