找回密码
 立即注册
首页 业界区 业界 补充:问题:CORS ,前后端访问跨域问题 ...

补充:问题:CORS ,前后端访问跨域问题

羊夏菡 昨天 23:08
补充:问题:CORS ,前后端访问跨域问题

我这边的解决方法是:
1.png
  1. myAxios.defaults.withCredentials = true; // 配置为true,表示前端向后端发送请求的时候,需要携带上凭证cookie
复制代码
整体的:
  1. import axios from "axios";
  2. // axios.defaults.withCredentials = true; // 允许携带凭证
  3. // const isDev = process.env.NODE_ENV === 'development';
  4. // 创建实例时配置默认值
  5. const myAxios = axios.create({
  6.     LookupAddress: undefined, LookupAddressEntry: undefined,
  7.     baseURL: 'http://localhost:8080/api'
  8. });
  9. // const myAxios: AxiosInstance = axios.create({
  10. //     baseURL: isDev ? 'http://localhost:8080/api' : '线上地址',
  11. // });
  12. myAxios.defaults.withCredentials = true; // 配置为true,表示前端向后端发送请求的时候,需要携带上凭证cookie
  13. // 创建实例后修改默认值
  14. // 添加请求拦截器
  15. myAxios.interceptors.request.use(function (config) {
  16.     // 在发送请求之前做些什么
  17.     console.log('我要发请求了')
  18.     return config;
  19. }, function (error) {
  20.     // 对请求错误做些什么
  21.     return Promise.reject(error);
  22. });
  23. // 添加响应拦截器
  24. myAxios.interceptors.response.use(function (response) {
  25.     // 2xx 范围内的状态码都会触发该函数。
  26.     // 对响应数据做点什么
  27.     console.log('我收到你的响应了',response)
  28.     return response.data;
  29. }, function (error) {
  30.     // 超出 2xx 范围的状态码都会触发该函数。
  31.     // 对响应错误做点什么
  32.     return Promise.reject(error);
  33. });
  34. // Add a request interceptor
  35. // myAxios.interceptors.request.use(function (config) {
  36. //     console.log('我要发请求啦', config)
  37. //     // Do something before request is sent
  38. //     return config;
  39. // }, function (error) {
  40. //     // Do something with request error
  41. //     return Promise.reject(error);
  42. // });
  43. //
  44. //
  45. // // Add a response interceptor
  46. // myAxios.interceptors.response.use(function (response) {
  47. //     console.log('我收到你的响应啦', response)
  48. //     // 未登录则跳转到登录页
  49. //     if (response?.data?.code === 40100) {
  50. //         const redirectUrl = window.location.href;
  51. //         window.location.href = `/user/login?redirect=${redirectUrl}`;
  52. //     }
  53. //     // Do something with response data
  54. //     return response.data;
  55. // }, function (error) {
  56. //     // Do something with response error
  57. //     return Promise.reject(error);
  58. // });
  59. export default myAxios;
复制代码
后端配置:
2.png

在 Spring Boot 中,可以通过在配置类中添加 @CrossOrigin 注解或实现 WebMvcConfigurer 接口并重写 addCorsMappings 方法来允许特定来源的跨域请求:
  1. package com.rainbowsea.yupao.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  5. /**
  6. * 跨域配置
  7. *
  8. */
  9. @Configuration
  10. public class WebMvcConfg implements WebMvcConfigurer {
  11.     @Override
  12.     public void addCorsMappings(CorsRegistry registry) {
  13.         //设置允许跨域的路径
  14.         registry.addMapping("/**")
  15.                 //设置允许跨域请求的域名
  16.                 //当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
  17.                 .allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http" +
  18.                         "://127.0.0.1:8083","http://127.0.0.1:8080","http://127.0.0.1:5173")
  19.                 //是否允许证书 不再默认开启
  20.                 .allowCredentials(true)
  21.                 //设置允许的方法
  22.                 .allowedMethods("*")
  23.                 //跨域允许时间
  24.                 .maxAge(3600);
  25.     }
  26. }
复制代码
相关博客链接:

  • https://blog.csdn.net/yuanlong12178/article/details/147143201 参考该 blog 解决的
  • https://blog.csdn.net/xhmico/article/details/122338365 这篇也不错。
3.png
  1. import { defineConfig } from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. // 导出配置对象,使用ES模块语法
  4. export default defineConfig({
  5.   plugins: [vue()], // 启用Vue插件
  6.   server: { // 注意:在Vite的新版本中,配置项`devServer`已更名为`server`
  7.     proxy: {
  8.       '/api': {
  9.         target: 'http://localhost:8080/api', // 目标服务器地址
  10.         changeOrigin: true, // 是否改变源
  11.         // 如果需要路径重写,可以取消以下行的注释
  12.         // pathRewrite: { 1'^/api': '' }
  13.       }
  14.     }
  15.   }
  16. });
复制代码
https://blog.csdn.net/yuanlong12178/article/details/147143201 内容备份如下:
一、Vue.js 中跨域请求未配置 CORS 的常见原因
(一)浏览器的同源策略限制
浏览器的同源策略限制了从一个源加载的文档或脚本与来自另一个源的资源之间的交互能力。当你的前端应用和后端 API 位于不同的域或端口时,就会触发 CORS 问题。
(二)后端未正确配置 CORS
如果后端服务器未正确设置 CORS 相关的响应头,浏览器将无法允许跨域请求。
二、解决方案

(一)后端配置 CORS

在后端服务器上进行 CORS 配置是解决跨域问题的根本方法。以下是一些常见后端框架的 CORS 配置示例:

  • Node.js (使用 Express)
  1. const express = require('express');
  2. const cors = require('cors');
  3. const app = express();
  4. app.use(cors({
  5.   origin: 'http://localhost:8080', // 允许的源
  6.   methods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的 HTTP 方法
  7.   allowedHeaders: ['Content-Type', 'Authorization'] // 允许的头部字段
  8. }));
  9. app.get('/api/data', (req, res) => {
  10.   res.json({ message: 'CORS is working!' });
  11. });
  12. app.listen(3000, () => {
  13.   console.log('Server is running on port 3000');
  14. });
复制代码
2. Spring Boot

在 Spring Boot 中,可以通过在配置类中添加 @CrossOrigin 注解或实现 WebMvcConfigurer 接口并重写 addCorsMappings 方法来允许特定来源的跨域请求:
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  5. @Configuration
  6. public class WebConfig implements WebMvcConfigurer {
  7.     @Override
  8.     public void addCorsMappings(CorsRegistry registry) {
  9.         registry.addMapping("/api/**")
  10.                 .allowedOrigins("http://localhost:8080")
  11.                 .allowedMethods("GET", "POST", "PUT", "DELETE")
  12.                 .allowCredentials(true);
  13.     }
  14. }
复制代码
(二)前端配置代理

在开发环境中,可以通过配置代理服务器来绕过浏览器的同源策略限制。Vue CLI 提供了代理配置功能,可以通过修改 vue.config.js 文件中的 devServer.proxy 选项来实现。
  1. module.exports = {
  2.   devServer: {
  3.     proxy: {
  4.       '/api': {
  5.         target: 'http://api.example.com', // 目标服务器
  6.         changeOrigin: true, // 是否改变源
  7.         pathRewrite: { '^/api': '' } // 路径重写
  8.       }
  9.     }
  10.   }
  11. };
复制代码
(三)使用第三方库

使用像 cors 这样的第三方库可以大大简化 CORS 的配置过程。安装库后,可以在后端应用中引入并配置它:
  1. const cors = require('cors');
  2. const express = require('express');
  3. const app = express();
  4. app.use(cors({
  5.   origin: 'http://localhost:8080',
  6.   methods: 'GET,POST,PUT,DELETE',
  7.   allowedHeaders: 'Content-Type,Authorization'
  8. }));
  9. // Rest of the server setup
复制代码
(四)JSONP(不推荐)

JSONP 是一种较老的跨域解决方案,通过 <script> 标签的跨域加载机制来实现。它只支持 GET 请求,且存在安全风险,因此在现代应用中不推荐使用。
三、最佳实践建议
(一)优先在后端配置 CORS
在生产环境中,优先在后端服务器上进行 CORS 配置,以确保安全性。
(二)开发环境使用代理
在开发环境中,使用 Vue CLI 的代理功能来解决跨域问题,避免修改后端代码。
(三)避免使用 JSONP
由于 JSONP 存在安全风险且只支持 GET 请求,建议避免使用。
四、总结
在 Vue.js 中,解决跨域请求未配置 CORS 的问题可以通过后端配置 CORS、前端配置代理、使用第三方库等方法来实现。后端配置 CORS 是最推荐的方法,因为它可以确保生产环境的安全性。在开发环境中,使用 Vue CLI 的代理功能可以快速解决跨域问题。希望本文的介绍能帮助你在 Vue.js 开发中更好地处理跨域请求,提升应用的性能和用户体验。
最后:

“在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。”
4.gif


来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册