當瀏覽器報以下錯誤時,則說明請求跨域了。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) })
源碼地址: 從這裏飛過去後端