设置请求头部
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做代理
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请求。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持菜鸟教程(cainiaojc.com)。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。