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)
})

源码地址: 从这里飞过去后端

相关文章
相关标签/搜索