vue 引入pdf跨域问题怎么解决_详解Vue 开发模式下跨域问题

本文介绍了前端开发中解决跨域问题的两种方法:通过axios配置withCredentials和后端设置CORS头,以及使用vue-cli的proxyTable进行代理。详细解释了配置过程,并指出JSONP的原理和限制,强调了代理方法在前端联调中的便利性。
摘要由CSDN通过智能技术生成

设置请求头部

后端设置请求头部Access-Control-Allow-Credentials: true和Access-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请求。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值