• Vue项目中跨域问题解决方案


     

    本文给大家介绍了vue项目中跨域问题的完美解决方案,通过更改header,使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
     

    方法

    • 后台更改header
    • 使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)
    • Jquery jsonp

    后台更改header

    1
    2
    header('Access-Control-Allow-Origin:*');//允许所有来源访问
    header('Access-Control-Allow-Method:POST,GET');//允许访问的方式

    使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)

    打开config/index.js,在proxyTable中添写如下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    proxyTable: {
     '/api': {
      target: '填写请求源地址', //源地址
      changeOrigin: true, //是否跨域
      pathRewrite: {
       '^/api': '' //路径重写
       }
     }
    }

    使用axios

    1
    2
    3
    4
    5
    this.$axios.post("/api/地址",{
      发送的数据
     }).then(data=>{
      console.log(data);
     })

    axios的配置(main.js)

    1
    2
    axios.defaults.headers.post["Content-type"]="application/json";
    Vue.prototype.$axios=axios;

    使用ES6fetch请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    fetch("/api/test/testToken.php",{
       method:"post",
       headers:{
        "Content-type":"application/json",
       },
       body:JSON.stringify({发送数据})
      }).then(result=>{
       return result.json()
      }).then(data=>{
       console.log(data);
      })

    使用jquery jsonp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    methods: {
     getData () {
      var self = this
      $.ajax({
       url: '地址',
       type: 'GET',
       dataType: 'JSONP',
       success: function (res) {
        self.data = res.data.slice(0, 3)
        self.opencode = res.data[0].opencode.split(',')
       }
      })
     }
    }
  • 相关阅读:
    中国VR公司的详尽名单
    maven打包源代码sources.jar和javadoc.jar帮助文档
    中国计算机学会推荐国际学术刊物
    myhuiban会议,期刊,科研人员,计算机类会议大全
    如何写mysql的定时任务
    mysql系列命令解释
    Bootstrap 导航元素
    base64对文件进行加密
    我最在行 诗词 连续错误的
    <% %> in html
  • 原文地址:https://www.cnblogs.com/gluncle/p/13025476.html
Copyright © 2020-2023  润新知