前后端分离,避免不了会出现跨域的问题!!于我而言,这时候我需要一个强大的后端的小哥;但后端小哥难免总会又没空的时候,这时候就只能靠自己了
创建vue.config.js
文件
// 方法1
module.exports = {
devServer: {
host: 'localhost',
port: '8083',
proxy: {
'/api': { // /api 表示拦截以/api开头的请求路径
target: 'http:127.0.0.1:3000', // 跨域的域名
changeOrigin: true, // 是否开启跨域
}
}
}
}
// 等同于
// 方法2
module.exports = {
devServer: {
host: 'localhost',
port: '8083',
proxy: {
'/api': {
target: 'http:127.0.0.1:3000/api',
changeOrigin: true,
pathRewrite: { // 重写路径
'^/api': '' // 把/api变为空字符
}
}
}
}
}
复制代码
理解:
// 请求接口:http://127.0.0.1:3000/api/newList
// axios请求
axios({
method: 'get',
url: '/api/newList'
}).then(res=>{})
// 上面请求接口可以分解为 127.0.0.1:3000 /api/newList
// 方法1 理解
// 当拦截到以/api开头路径时,把设置的跨域域名与路径拼接就变为了 http:127.0.0.1:3000/api/newList
// 方法2 理解
// 当拦截到以/api开头路径时,把设置的跨域域名与路径拼接就变为了 http:127.0.0.1:3000/api/api/newList
复制代码
见下图:
这样跨域就能解决了,以上仅个人理解,如有错误,欢迎指出
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END