网络请求采用jquery,Axios vue-resource均可以,这里采用vue-resourcephp
安装:cnpm install vue-resourcevue
创建server/index.jsjquery
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;
在模板使用:ios
<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报错)nginx
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.npm
调试的解决方案:后端
在config/index.js 下配置 30 行的 proxyTableapi
proxyTable: { //可配置多个规则 '/api': { target: 'http://localhost', //服务器端地址 changeOrigin:true, //忽略请求的origin pathRewrite: { '^/api': '/test/api' //url重写规则,能够配置多个 } } },
配置成功后重启 才会生效 !!!!!!跨域
在服务器端的解决方案:服务器
配置nginx反向代理,或者打包后和后端服务器代码放一块儿