以获取https://www.bilibili.com/index/ding.json为例
在vue.config.js里设置跨域
devServer: {
proxy: {
'/api': {
target: 'https://www.bilibili.com/index', //这里写要跨域的地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}}
/*
要注意的是 如果设置了生产环境的baseURL,请把生产环境的baseURL=’’;
在请求时,刚才写在target上的跨域地址 用api代替就可以
ps:
vue.config.js 页
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'https://www.bilibili.com/index',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
})
axios的请求模块
export const getdata = () => {
return request({
url: 'api/ding.json',
method:'get'
})
}
//请求
methods: {
jump() {
getdata().then((res) => {
console.log(res);
});
},
}
//请求返回的数据
解决了生产环境下不能跨域请求的问题;
!!!设置了baseURL的一定要把地址改成'',在发送请求时,刚才在跨域里设置的target(跨域的地址)用'api'代替即可ps:
跨域设置的 target: 'https://www.bilibili.com/index', //这里写要跨域的地址
在真正发送请求时 https://www.bilibili.com/index 用api代替即可
export const getdata = () => {
return request({
url: 'api/ding.json',
method:'get'
})
}
/*新人勿喷,欢迎指正;3Q*/