vue2.0 proxyTable配置,解決跨域

vue瀏覽器跨域問題及解決辦法

1、 問題

當瀏覽器報以下錯誤時,則說明請求跨域了。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.

clipboard.png

  • 爲何會跨域:
    由於瀏覽器同源策略的限制,不是同源的腳本不能操做其餘源下面的對象。

  • 什麼是同源策略:
    同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,若是缺乏了同源策略,則瀏覽器的正常功能可能都會受到影響。能夠說Web是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。

    簡單的來講:協議、IP、端口三者都相同,則爲同源vue

    clipboard.png

2、解決辦法

跨域的解決辦法有不少,好比script標籤jsonp後端設置cros等等...,可是我這裏講的是webpack配置vue 的 proxyTable解決跨域。webpack

這裏我請求的地址是 http://www.thenewstep.cn/test/testToken.phpios

那麼在ProxyTable中具體配置以下:git

clipboard.png

proxyTable: {
      '/apis': {
        // 測試環境
        target: 'http://www.thenewstep.cn/',  // 接口域名
        changeOrigin: true,  //是否跨域
        pathRewrite: {
            '^/apis': ''   //須要rewrite重寫的,
        }              
      }

target:就是須要請求地址的接口域名github

這裏列舉了2種數據請求方式: 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)
})

源碼地址: 從這裏飛過去後端

相關文章
相關標籤/搜索