vue proxyTable中跨域中pathRewrite配置

川长思鸟来 2021-09-28 13:24 520阅读 0赞

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进行代理时,对请求路径进行重定向以匹配到正确的请求地址,

  1. dev: {
  2. // Paths
  3. assetsSubDirectory: 'static',
  4. assetsPublicPath: '/',
  5. proxyTable: {
  6. '/api': {
  7. target: 'http://XX.XX.XX.XX:8083',
  8. changeOrigin: true,
  9. pathRewrite: {
  10. '^/api': '/api' // 这种接口配置出来 http://XX.XX.XX.XX:8083/api/login
  11. //'^/api': '/' 这种接口配置出来 http://XX.XX.XX.XX:8083/login
  12. }
  13. }
  14. }
  15. },

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

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

    // 获取菜单权限

    1. getPermission(){
    2. this.$ajaxget({
    3. url: '/api/getPermission',
    4. data: { },
    5. isLayer: true,
    6. successFc: data => {
    7. console.log(data.data)
    8. }
    9. })

2种数据请求方式: fecth和axios

1、 fetch方式:

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

  1. fetch("/apis/test/testToken.php", {
  2. method: "POST",
  3. headers: {
  4. "Content-type": "application/json",
  5. token: "f4c902c9ae5a2a9d8f84868ad064e706"
  6. },
  7. body: JSON.stringify(data)
  8. })
  9. .then(res => res.json())
  10. .then(data => {
  11. console.log(data);
  12. });

2、axios方式:

main.js代码

  1. import Vue from 'vue'
  2. import App from './App'
  3. import axios from 'axios'
  4. Vue.config.productionTip = false
  5. Vue.prototype.$axios = axios //将axios挂载在Vue实例原型上
  6. // 设置axios请求的token
  7. axios.defaults.headers.common['token'] = 'f4c902c9ae5a2a9d8f84868ad064e706'
  8. //设置请求头
  9. axios.defaults.headers.post["Content-type"] = "application/json"

axios请求页面代码

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

发表评论

表情:
评论列表 (有 0 条评论,520人围观)

还没有评论,来说两句吧...

相关阅读