Vue 开发模式下跨域问题

作者: 45b645c5912e | 来源:发表于2017-06-05 10:10 被阅读392次
  • 设置请求头部
  • 后端设置请求头部Access-Control-Allow-Credentials: trueAccess-Control-Allow-Origin: www.xxx.com
  • 前端post请求设置withCredentials=true
  • 这里用了axios的请求数据方法代码如下:
import axios from 'axios'
import config from '../config'
export default {
  request (method, uri, data, headerConfig = {withCredentials: true}) {
    if (!method) {
      console.error('API function call requires method argument')
      return
    }

    if (!uri) {
      console.error('API function call requires uri argument')
      return
    }

    let url = config.serverURI + uri

    return axios({ method, url, data, ...headerConfig })
  }
}
  • jQuery的$.ajax::
$.ajax({
    type: "POST",
    url: "http://www.xxx.com/api.php",
    dataType: 'json',
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true
}).then((json) => {
    // balabala...
})
  • 使用nodejs做代理
  • 上面的那种方法需要后端配合设置头部,对于我这种前端小白来讲,联调时各种不成功的报错也无从解决,所以个人比较倾向于下面这种做法,鉴于使用脚手架vue-cli创建的项目,作者已经给我提供好了解决的方法。
  • 找到项目文件夹下的config/index.js, 里面有一行proxyTable: {}, 这里就是作者为我们留的接口, 我们添加代理规则进去
var path = require('path')
module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../xxx/index.html'),
    assetsRoot: path.resolve(__dirname, '../xxx'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true,
    productionGzip: false,
    productionGzipExtensions: ['js', 'css']
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://www.xxx.com/api.php/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/'
        }
      }
    },
    cssSourceMap: false
  }
}
  • 这里target为目标域名,pathRewrite为转换规则,请求数据时将接口地址 根据转换规则请求就可以解决跨域啦!(这里也可以配置headers,设置cookis,token等)
  • jsonp
  • jsonp也是一种解决跨域的方法,不过我从来没有用过,在网上查了下资料,jsonp的原理是script标签引入js是不受域名限制的, 由于是模拟插入script标签, 所以不可以用post请求。

相关文章

  • Vue 开发模式下跨域问题

    设置请求头部 后端设置请求头部Access-Control-Allow-Credentials: true和Acc...

  • ajax 请求

    Vue开发中解决跨域问题 Axios 配置请求拦截

  • Vue跨域请求

    在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的。 1、当跨域无法...

  • vue-cli脚手架项目中的跨域解决方案

    1、在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的。 2、当跨域...

  • 完美解决 Spring Boot + Vue Axios 跨域

    前言 前后台分离开发模式越来越来成为主流,刚接触这种开发模式时,我们必定会遇到一个问题: 跨域。 跨域 产生跨域问...

  • Django+vue跨域问题解决

    跨域 由于开发模式为前后端分离式开发,故而通常情况下,前端和后端可能运行不同的ip或者port下,导致出现跨域问题...

  • 解决一例Vue跨域访问无效

    在使用vue开发的时候经常要涉及到跨域的问题,其实在vue cli中是有我们设置跨域请求的文件的。当跨域无法请求的...

  • 解决Vue http中的跨域问题

    在平常的项目开发当中,很容易遇到跨域的问题,好在vue-cli的脚手架提供了跨域的解决方案,在config下的in...

  • vue 开发模式跨域

    module.exports 的 dev 区块,设置代理

  • 前端处理跨域的四种方案

    在前后端分离的开发模式广泛应用的过程中,我们不得不面对跨域这个问题,而为什么会出现跨域呢?什么情况下称为跨域呢? ...

网友评论

    本文标题:Vue 开发模式下跨域问题

    本文链接:https://www.haomeiwen.com/subject/rdhifxtx.html