Vue.js前端框架解决跨域问题
1.使用代理 :
在vue.config.js文件中配置代理,将请求发送到与前端同域的服务器,再由服务器发送到目标地址。这种方法需要后端人员协助设置。
这样,在发送请求时,只需要将请求地址设置为 /api 开头的地址即可。例如:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
pathRewrite: {
'/api': ''
}
}
}
}
}
2.使用JSONP方式发送跨域请求:
使用JSONP方式发送跨域请求,通过在前端动态创建一个script标签,并将地址设置为目标地址,再在目标地址返回的js中调用前端定义的回调函数,以实现跨域请求。
export function getData () {
const url = 'http://example.com/data?callback=getDataCallback'
return new Promise((resolve, reject) => {
window.getDataCallback = function (data) {
resolve(data)
}
const script = document.createElement('script')
script.src = url
document.body.appendChild(script)
})
}
3.CORS:
在后端接口中添加CORS(跨域资源共享)头部信息,允许前端跨域访问。
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type")
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
next()
})
4.使用第三方库:
使用第三方库如axios、fetch等发送跨域请求,这些库已经封装了跨域处理的方法。例如在axios中,可以通过设置withCredentials: true开启跨域请求。
import axios from 'axios'
axios.defaults.withCredentials = true
export function getData () {
return axios.get('http://example.com/data')
.then(res => res.data)
}