axios跨域处理

本质分析:

因为axios在vue中利用中间件http-proxy-middleware做了一个本地的代理服务A,相当于你的浏览器通过本地的代理服务A请求了服务端B,
浏览器通过服务A并没有跨域,因此就绕过了浏览器的同源策略,解决了跨域的问题。

一、 问题

当浏览器报如下错误时,则说明请求跨域了。

localhost/:1 Failed to load http://www.thenewstep.cn/test/testToken.php: Response topreflight 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 fetchthe resource with CORS disabled.

  

  • 为什么会跨域:
    因为浏览器同源策略的限制,不是同源的脚本不能操作其他源下面的对象。

  • 什么是同源策略:
    同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

    简单的来说:协议、IP、端口三者都相同,则为同源

二、解决办法

跨域的解决办法有很多,比如script标签 、jsonp后端设置cros等等...,但是我这里讲的是webpack配置vue 的 proxyTable解决跨域。

这里我请求的地址是 http://www.thenewstep.cn/test/testToken.php

那么在ProxyTable中具体配置如下:

proxyTable: {
      '/apis': {
        // 测试环境
        target: 'http://www.thenewstep.cn/',  // 接口域名
        changeOrigin: true,  //是否跨域
        pathRewrite: {
            '^/apis': ''   //需要rewrite重写的,
        }              
      }

target:就是需要请求地址的接口域名

这里列举了2种数据请求方式: fecth和axios

1、 fetch方式:

在需要请求的页面,只需要这样写(/apis+具体请求参数),如下:

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

2、axios方式:

main.js代码

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请求页面代码

this.$axios.post('/apis/test/testToken.php',data).then(res=>{
        console.log(res)
})

.

猜你喜欢

转载自www.cnblogs.com/jianxian/p/11939293.html