首页 前端知识 vue.config.js 配置proxy代理

vue.config.js 配置proxy代理

2024-06-21 00:06:39 前端知识 前端哥 279 161 我要收藏

方案一: 配置文件

文件内容

# 开发环境
NODE_ENV = 'development'
# base api
VUE_APP_BASE_API = '/api'
# 开发环境,Url地址
VUE_APP_URL = 'https://localhost:44367/api'
复制

三个文件分别是三个不同环境使用的,如线上,线上测试,本地测试。我在本地测试时三个文件都配置成了一样。

 vue.config.js 配置文件

const path = require('path');
const resolve = dir => {
return path.join(__dirname, dir);
};
const env = process.env.NODE_ENV;
console.info('env: ------>', env, 'api:------>', process.env.VUE_APP_URL,'VUE_APP_BASE_API:-->',process.env.VUE_APP_BASE_API);
module.exports = {
// mode: 'production',
publicPath: process.env.NODE_ENV === 'production' ? './' : './', // 启动页地址
// publicPath: './', // 启动页地址
outputDir: "dist", // 打包的目录
indexPath: 'index.html', // 生成html文件名
assetsDir: 'static', // 静态资源文件目录
runtimeCompiler: true,
lintOnSave: false, // 在保存时校验格式
productionSourceMap: false, // 生产环境是否生成 SourceMap
/*
chainWebpack: config => {
// 修复热更新
config.resolve.symlinks(true);
},
*/
devServer: {
/*1.测试成功 配合配置文件使用 VUE_APP_URL = 'https://localhost:44367/api'*/
proxy: {
[process.env.VUE_APP_BASE_API]: {// api 表示拦截以 /api开头的请求路径
target: process.env.VUE_APP_URL,//跨域的域名(不需要写路径)
changeOrigin: true, //是否开启跨域
ws: true, //是否代理websocked
pathRewrite: { //重写路径
['^' + process.env.VUE_APP_BASE_API]: ''//把 /api 变为空字符
}
},
},
/*2.测试成功 配置写死 target 不带/api,注意没有pathRewrite属性,调用接口时这么写 api/User/gettest*/
/* port: 8088,
proxy: {
'/api': {// api 表示拦截以 /api开头的请求路径
target : 'https://localhost:44367',//跨域的域名(不需要写路径)process.env.VUE_APP_URL
changeOrigin : true, //是否开启跨域
ws: true, //是否代理websocked
},
},
/*3.测试成功 配置写死 target 带/api,注意要加pathRewrite属性,调用接口时这么写 api/User/gettest*/
/*
proxy: {
'/api': {// api 表示拦截以 /api开头的请求路径
target : 'https://localhost:44367/api',//跨域的域名(不需要写路径)process.env.VUE_APP_URL
changeOrigin : true, //是否开启跨域
ws: true, //是否代理websocked
pathRewrite : { //重写路径
'^/api' : '' //把 /api 变为空字符
}
},
}, */
}
}
复制

问题:

控制台显示 400 (Bad Request)或404等问题都是 vue.config.js 配置文件 的 proxy 的配置问题。

主要检查点是  target 里没有带 /api 和  pathRewrite 属性的问题。

如果使用配置文件要检查 

VUE_APP_BASE_API = '/api' 这里要小心,要注意有没有带 /复制
VUE_APP_URL = 'https://localhost:44367/api' 这里也要检查要和vue.config.js 配置文件里的代码配合使用。复制

END

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13066.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!