Vue3解决前端跨域问题

在vue.config.js里添加代理

备注:例如vue想请求不在同一台服务器上的localhost:8080服务器的接口,在下面proxy里的target里写上要访问的服务器的前缀,然后写一个别名'/projectURL',

 

 1 const {defineConfig} = require('@vue/cli-service')
 2 module.exports = defineConfig({
 3         transpileDependencies: true,
 4         lintOnSave: false,//关闭语法检查
 5 
 6         // 基本路径
 7         publicPath: '/',
 8         // 输出文件目录
 9         outputDir: 'dist',
10         configureWebpack: {
11             externals: {}
12         },
13         devServer: {
14             proxy: {
15                 '/projectURL': {
16                     target: 'http://localhost:8080/',  //这里是后端接口的 IP+端口
17                     ws: true,//代理websocked
18                     changeOrigin: true,
19                     secure: false, //target是否为https接口
20                     pathRewrite: {
21                         '^/projectURL': ''  //更改请求URL
22                     }
23                 },
24                 '/otherUrl': {
25                     target: 'https://××××××××.com/',  //请求对象
26                     ws: true,//代理websocked
27                     changeOrigin: true,
28                     secure: true, //target是否为https接口
29                     pathRewrite: {
30                         '^/otherUrl': ''  //更改请求URL
31                     }
32                 }
33             }
34         }
35     }
36 )

然后在访问的页面写上:

import axios from "axios";
axios.defaults.baseURL = "/projectURL";

然后:请求时当前页面axios里不用在写访问的接口的IP了,axios.defaults.baseURL = "/projectURL";这里已经指定了当前访问的就是代理里定义的域名或者IP了

1 axios.get("/a/getUser", {})
2 
3           .then((response) => {
4 
5             console.log(response);
6 
7           });

 

如果部署到Nginx上请求后端接口报404 ,请看我另一篇文章

https://www.cnblogs.com/lwl80/p/16640842.html

posted @ 2022-11-15 20:28  勤快的懒羊羊  阅读(2704)  评论(0编辑  收藏  举报