VUE反向代理怎么配置?如何防止本地开发时接口调用跨域问题?

在vue开发中,经常会遇到跨域问题。那么比较常见的前端处理方法就是配置反向代理,如何配置呢?

1.前往根目录,创建vue.config.js文件;

 2.编写配置:

 1 const path = require('path');
 2 // const ZipPlugin = require('zip-webpack-plugin');
 3 let zipName = 'dist';
 4 module.exports = {
 5     transpileDependencies:['@dcloudio/uni-ui'],
 6 
 7     publicPath: './',
 8     // chainWebpack: config => {
 9     //     // 打包ZIP
10     //     config.plugin('zip').use(ZipPlugin, [{
11     //         path: path.join(__dirname, 'dist'),
12     //         filename: `${zipName}.zip`
13     //     }]);
14     // },
15     //配置一些目录的精简访问方式
16     configureWebpack: {
17         resolve: {
18             alias: {
19                 '@': path.join(__dirname, 'src'),
20                 'assets': path.join(__dirname, 'src/assets'),
21                 'components': path.join(__dirname, 'src/components')
22             }
23         },
24         devServer: {
25             client: {
26                 overlay: false
27             },
28             //注意,配置反向代理后,需重新执行yarn serve 运行
29             proxy: {
30                 '/nmediaapi': {     //资讯
31                     target: "http://dev.example.cn",
32                     changeOrigin: true,
33                     ws: true,
34                 },
35                 '/activityMallapi': {   //智能数据
36                     target: "http://dev.example.cn",
37                     changeOrigin: true,
38                     ws: true,
39                 },
40                 '/footballapi': {    //赛事              
41                     target: "http://dev.example.cn",
42                     changeOrigin: true,
43                     ws: true,
44                 },
45                 '/userapi': {        //用户          
46                     target: "http://dev.example.cn",
47                     changeOrigin: true,
48                     ws: true,
49                 },
50                 '/nmedia':{         //新媒体      
51                     target: "http://dev.example.cn",
52                     changeOrigin: true,
53                     ws: true,
54                 },
55                 '/recommendapi':{    //推荐          
56                     target: "http://dev.example.cn",
57                     changeOrigin: true,
58                     ws: true,
59                 }
60             }
61         }
62     }
63 }

3.以上配置完成后,即可编写请求方法,访问接口,例如 

原网址:http://dev.example.cn/activityMallapi/bigDataPursuit/ai/getModelTag
代理到:http://localhost:8080/activityMallapi/bigDataPursuit/ai/getModelTag

 这样就能请求成功,返回200。

 

posted @ 2025-01-17 11:31  coderjim  阅读(98)  评论(0)    收藏  举报

更多知识请点击——

www.7017online.xyz