标题:vue.js 跨域请求 fetch / axios 出处:刘新修 时间:Wed, 28 Aug 2019 13:48:16 +0000 作者:刘新修 地址:http://liuxinxiu.com:80/s/291/ 内容: 假设我们的请求地址:http://localhost/Graduation_Thesis/a.php 在vue项目下 找到 config > index.js 文件;修改 index.js 文件下的 proxyTable 对象的内容;如下 JavaScript代码 proxyTable: { '/api': { // '/api'相当于代表 http://localhost/Graduation_Thesis 可自行修改名字 target: 'http://localhost/Graduation_Thesis', //我们需要请求的主要文件夹地址 changeOrigin: true, //是否跨域 pathRewrite: { '^/api': '' //路径重写 } } }, 这样就可以跨域请求 http://localhost/Graduation_Thesis 下的文件了,而需要获取文件下的 a.php 文件 需要用 fetch/ 来做请求 fetch 请求fetch 类似于 ajax 数据提交,但 fetch 更好 JavaScript代码 export default { name: 'App', components: { appHeader:Header }, created(){ fetch('/api/a.php',{ // /api既是上面跨域定义的文件地址 method:"post", //请求方式 headers: { //请求头 'Content-Type': 'application/json', 'Accept': 'application/json' }, body:{ //发送的请求内容 username:'hw', pass:'123' } }).then(res => { return res.json(); }).then(res => { console.log(res); }) } } axios 请求首先全局安装 JavaScript代码 npm install axios 在 mian.js 引用 JavaScript代码 //main.js import axios from 'axios' //让 axios 可以全局使用 Vue.prototype.$axios = axios 这样就可以开始使用了 JavaScript代码 export default { name: 'App', components: { appHeader:Header }, created(){ this.$axios.post("/api/a.php",{ username:'hw', pass:'1123' }) .then(res =>{ console.log(res); }) } } Generated by Bo-blog 2.1.1 Release