当浏览器报以下错误时,则说明请求跨域了。php
localhost/:1 Failed to load http://www.thenewstep.cn/test/testToken.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
同源策略
的限制,不是同源的脚本不能操做其余源下面的对象。同源策略
:简单的来讲:协议、IP、端口三者都相同,则为同源
vue
跨域的解决办法有不少,好比script标签
、jsonp
、后端设置cros
等等...,可是我这里讲的是webpack配置vue 的 proxyTable
解决跨域。webpack
这里我请求的地址是 http://www.thenewstep.cn/test/testToken.php
ios
那么在ProxyTable中具体配置以下:git
proxyTable: { '/apis': { // 测试环境 target: 'http://www.thenewstep.cn/', // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { '^/apis': '' //须要rewrite重写的, } }
target:就是须要请求地址的接口域名github
fecth和axios
fetch
方式:在须要请求的页面,只须要这样写(/apis+具体请求参数),以下:web
fetch("/apis/test/testToken.php", { method: "POST", headers: { "Content-type": "application/json", token: "f4c902c9ae5a2a9d8f84868ad064e706" }, body: JSON.stringify(data) }) .then(res => res.json()) .then(data => { console.log(data); });
axios
方式:main.js代码json
import Vue from 'vue' import App from './App' import axios from 'axios' Vue.config.productionTip = false Vue.prototype.$axios = axios //将axios挂载在Vue实例原型上 // 设置axios请求的token axios.defaults.headers.common['token'] = 'f4c902c9ae5a2a9d8f84868ad064e706' //设置请求头 axios.defaults.headers.post["Content-type"] = "application/json"
axios请求页面代码axios
this.$axios.post('/apis/test/testToken.php',data).then(res=>{ console.log(res) })
源码地址: 从这里飞过去后端