vue proxyTable的跨域中pathRewrite配置方式_vue.js

2022年4月20日08:28:33

vue浏览器跨域问题和vue proxyTable跨域中pathRewrite配置

vue浏览器跨域问题

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

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.

为什么会跨域

因为浏览器同源策略的限制,不是同源的脚本不能操作其他源下面的对象。

什么是同源策略

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。

可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

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

解决办法

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

pathRewrite

简单来说,pathRewrite是使用proxy进行代理时,对请求路径进行重定向以匹配到正确的请求地址,

dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://XX.XX.XX.XX:8083',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api'   // 这种接口配置出来     http://XX.XX.XX.XX:8083/api/login
          //'^/api': '/' 这种接口配置出来     http://XX.XX.XX.XX:8083/login
        }
      }
    }
  },

如何不配置pathRewrite 请求就被转发到 http://XX.XX.XX.XX:8083 并把相应uri带上。

比如:localhost:8080/api/xxx 会被转发到http://XX.XX.XX.XX:8083/api/xxx

配置完成后需要重新编译一遍 , 调用接口的时候

        // 获取菜单权限
      getPermission(){
        this.$ajaxget({
          url: '/api/getPermission',
          data: {},
          isLayer: true,
          successFc: data => {
            console.log(data.data)
          }
        })

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

代理配置proxy下pathrewrite失效踩坑

从网上直接找到的代码复制过来报错,最后找了一下午为什么失效,最后发现问题直接破防了

错误:

pathRewrite: { 
  "  ^/api  "  : "" //若请求的路径在目标url下但不在/api 下,则将其转换成空
  },

正确:

pathRewrite: { 
  "^/api": "" //若请求的路径在目标url下但不在/api 下,则将其转换成空
   },

原因:

直接复制过来的 "  ^/api  "  : ""里面多了两个空格,判断url的时候就获取不到/api,删除空格就解决问题了

  • 作者:BraveSoul360  
  • 原文链接:https://blog.csdn.net/yunfeng482/article/details/89883970
    更新时间:2022年4月20日08:28:33 ,共 2437 字。