vue 403 Invalid CORS request

时间: 2024-06-09 09:05:51 浏览: 334
引用: CORS (Cross-Origin Resource Sharing)是一种浏览器的安全策略,用于控制跨域资源的访问。当浏览器发起跨域请求时,如果目标资源的响应头没有包含正确的CORS策略,浏览器会阻止该请求。错误信息"Access to XMLHttpRequest at 'http://10.1.1.1:8080/web-api/login' from origin 'http://xxx.com' has been blocked by CORS policy"提示你的请求被CORS策略拦截了。 引用: 出现这个错误的原因可能是你的代码中使用了写死的接口请求地址,并且该地址不是相对路径,而是绝对路径。为了避免CORS错误,你需要将这些写死的地址改为相对路径的方式,例如改为“/web-api/xxx”。 引用: 如果你的代码是基于Vue框架开发的,可以在配置文件(比如webpack配置文件)中设置API_ROOT为相对路径。例如,将API_ROOT设置为空字符串,HOST设置为"localhost"。 解决CORS错误的关键是确保请求的源和目标资源在同一个域下,或者目标资源的响应头包含了适当的CORS策略。请根据上述引用内容中提供的方法尝试解决你的问题。
相关问题

Vue应用请求SpringBoot API出现 CORS 跨域请求设置 Invalid CORS request错误

这个错误是因为浏览器的同源策略所导致的,同源策略要求请求的协议、域名、端口号必须全部匹配,否则就会出现跨域问题。 要解决这个问题,有两种方法: 1. 在 SpringBoot 中配置 CORS。在 SpringBoot 的配置文件中,可以添加如下配置: ``` @Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*"); } }; } } ``` 这段代码表示允许所有来源(`allowedOrigins("*")`)、所有方法(`allowedMethods("*")`)和所有请求头(`allowedHeaders("*")`)的跨域请求。 2. 在 Vue 应用中使用代理。在 Vue 应用的 `config/index.js` 文件中,可以添加如下配置: ``` module.exports = { dev: { proxyTable: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '/api' } } } } } ``` 这段代码表示将所有以 `/api` 开头的请求代理到 `http://localhost:8080`,并开启跨域请求支持(`changeOrigin: true`)。在 Vue 应用中,请求的 URL 可以写成 `/api/xxx` 的形式,这样就会被代理到目标服务器。

实例: vue3 用store保存登录用户信息 前台用vue3 后台Springboot 假设有一个users表,用security来判定,工具前后端都使用idea

好的,下面是一个简单的实例,演示如何使用Vue3和Spring Boot来实现用户登录和保存用户信息到Vuex store中。 前端部分: 1. 创建Vue3项目并安装Vuex库: ``` vue create myproject cd myproject npm install vuex --save ``` 2. 在src目录下创建store目录,并新建一个index.js文件来定义和导出Vuex store: ```javascript import { createStore } from 'vuex' const store = createStore({ state: { user: null }, mutations: { setUser(state, user) { state.user = user }, clearUser(state) { state.user = null } }, actions: { login({ commit }, user) { // Send login request to the backend // ... // If login succeeds, commit the user to the store commit('setUser', user) }, logout({ commit }) { // Send logout request to the backend // ... // If logout succeeds, clear the user in the store commit('clearUser') } }, getters: { isLoggedIn(state) { return !!state.user }, getUser(state) { return state.user } } }) export default store ``` 3. 在main.js中导入store并挂载到Vue实例中: ```javascript import { createApp } from 'vue' import App from './App.vue' import store from './store' createApp(App).use(store).mount('#app') ``` 4. 在登录页面中创建一个表单来输入用户名和密码,并将其提交到Vuex store中: ```html <template> <form @submit.prevent="login"> <input v-model="username" placeholder="Username"> <input v-model="password" placeholder="Password"> <button type="submit">Login</button> </form> </template> <script> import { mapActions } from 'vuex' export default { data() { return { username: '', password: '' } }, methods: { ...mapActions(['login']), onSubmit() { this.login({ username: this.username, password: this.password }) } } } </script> ``` 5. 在需要访问用户信息的组件中,使用Vuex的mapGetters函数来获取用户信息: ```html <template> <div v-if="isLoggedIn"> Logged in as: {{ username }} <button @click="logout">Logout</button> </div> <div v-else> Not logged in </div> </template> <script> import { mapGetters, mapActions } from 'vuex' export default { computed: { ...mapGetters(['isLoggedIn', 'getUser']), username() { return this.getUser.username } }, methods: { ...mapActions(['logout']) } } </script> ``` 后端部分: 1. 使用Spring Boot创建一个RESTful API,用于处理用户登录和注销请求: ```java @RestController @RequestMapping("/api/auth") public class AuthController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenProvider tokenProvider; @Autowired private UserRepository userRepository; @PostMapping("/login") public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( loginRequest.getUsernameOrEmail(), loginRequest.getPassword() ) ); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = tokenProvider.generateToken(authentication); return ResponseEntity.ok(new JwtAuthenticationResponse(jwt)); } @PostMapping("/logout") public ResponseEntity<?> logoutUser(HttpServletRequest request) { // Invalidate session and clear authentication token HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } SecurityContextHolder.clearContext(); return ResponseEntity.ok(new ApiResponse(true, "Successfully logged out")); } } ``` 2. 创建一个User实体类,并创建一个UserRepository接口来访问users表: ```java @Entity @Table(name = "users") public class User extends DateAudit { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank @Size(max = 40) private String name; @NotBlank @Size(max = 15) private String username; @NaturalId @NotBlank @Size(max = 40) @Email private String email; @NotBlank @Size(max = 100) private String password; // getters and setters } @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByEmail(String email); Boolean existsByEmail(String email); } ``` 3. 使用Spring Security来保护API,并使用JwtTokenProvider类来生成和验证JWT: ```java @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService customUserDetailsService; @Autowired private JwtAuthenticationEntryPoint unauthorizedHandler; @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(customUserDetailsService) .passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/auth/**") .permitAll() .anyRequest() .authenticated(); // Add JwtAuthenticationFilter http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } } @Component public class JwtTokenProvider { private static final Logger logger = LoggerFactory.getLogger(JwtTokenProvider.class); @Value("${app.jwtSecret}") private String jwtSecret; @Value("${app.jwtExpirationInMs}") private int jwtExpirationInMs; public String generateToken(Authentication authentication) { UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); Date now = new Date(); Date expiryDate = new Date(now.getTime() + jwtExpirationInMs); return Jwts.builder() .setSubject(Long.toString(userPrincipal.getId())) .setIssuedAt(new Date()) .setExpiration(expiryDate) .signWith(SignatureAlgorithm.HS512, jwtSecret) .compact(); } public Long getUserIdFromJWT(String token) { Claims claims = Jwts.parser() .setSigningKey(jwtSecret) .parseClaimsJws(token) .getBody(); return Long.parseLong(claims.getSubject()); } public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); return true; } catch (SignatureException ex) { logger.error("Invalid JWT signature"); } catch (MalformedJwtException ex) { logger.error("Invalid JWT token"); } catch (ExpiredJwtException ex) { logger.error("Expired JWT token"); } catch (UnsupportedJwtException ex) { logger.error("Unsupported JWT token"); } catch (IllegalArgumentException ex) { logger.error("JWT claims string is empty."); } return false; } } ``` 以上就是一个简单的使用Vue3和Spring Boot实现用户登录和保存用户信息到Vuex store中的实例。其中,涉及到了Vue3的Vuex库、Spring Boot的RESTful API、Spring Security和JwtTokenProvider等技术,需要在前后端都进行配置和编码。
阅读全文

相关推荐

最新推荐

recommend-type

Vue框架总结.pdf

Vue.js 是一款流行的前端JavaScript框架,它以声明式的数据绑定和组件化开发为特点,极大地提高了Web应用的构建效率。Vue CLI是Vue.js官方提供的一个命令行工具,用于快速搭建和管理Vue项目,简化开发流程。 Vue ...
recommend-type

解决Vue axios post请求,后台获取不到数据的问题方法

在Vue中,axios通常被用来发起异步请求,它支持Promise API,方便与Vue的Promise-based API集成。POST请求的基本语法如下: ```javascript axios.post(url, data, config) .then(response =&gt; { // 处理成功响应 ...
recommend-type

vue项目中使用天地图

在Vue项目中集成天地图,可以为Web应用提供丰富的地理信息展示功能。下面将详细介绍如何在Vue项目中实现这一过程,以及如何添加一些基本的地图操作。 首先,你需要在天地图官方网站...
recommend-type

vue写h5页面的方法总结

在使用Vue.js编写H5页面时,我们需要考虑的首要任务是布局、样式和不同设备的适配。Vue.js作为一个强大的渐进式JavaScript框架,能够帮助我们构建高效、可维护的前端应用,同样适用于H5页面的开发。以下是一些关键...
recommend-type

Vue实现Layui的集成方法步骤

在Vue项目中集成Layui,主要是为了利用Layui提供的丰富UI组件和功能,例如在线客服系统layim。以下是一步一步详细说明如何在Vue项目中集成Layui: 1. **获取Layui** - Layui官方提供了npm安装方式。在商业项目中,...
recommend-type

Spring Websocket快速实现与SSMTest实战应用

标题“websocket包”指代的是一个在计算机网络技术中应用广泛的组件或技术包。WebSocket是一种网络通信协议,它提供了浏览器与服务器之间进行全双工通信的能力。具体而言,WebSocket允许服务器主动向客户端推送信息,是实现即时通讯功能的绝佳选择。 描述中提到的“springwebsocket实现代码”,表明该包中的核心内容是基于Spring框架对WebSocket协议的实现。Spring是Java平台上一个非常流行的开源应用框架,提供了全面的编程和配置模型。在Spring中实现WebSocket功能,开发者通常会使用Spring提供的注解和配置类,简化WebSocket服务端的编程工作。使用Spring的WebSocket实现意味着开发者可以利用Spring提供的依赖注入、声明式事务管理、安全性控制等高级功能。此外,Spring WebSocket还支持与Spring MVC的集成,使得在Web应用中使用WebSocket变得更加灵活和方便。 直接在Eclipse上面引用,说明这个websocket包是易于集成的库或模块。Eclipse是一个流行的集成开发环境(IDE),支持Java、C++、PHP等多种编程语言和多种框架的开发。在Eclipse中引用一个库或模块通常意味着需要将相关的jar包、源代码或者配置文件添加到项目中,然后就可以在Eclipse项目中使用该技术了。具体操作可能包括在项目中添加依赖、配置web.xml文件、使用注解标注等方式。 标签为“websocket”,这表明这个文件或项目与WebSocket技术直接相关。标签是用于分类和快速检索的关键字,在给定的文件信息中,“websocket”是核心关键词,它表明该项目或文件的主要功能是与WebSocket通信协议相关的。 文件名称列表中的“SSMTest-master”暗示着这是一个版本控制仓库的名称,例如在GitHub等代码托管平台上。SSM是Spring、SpringMVC和MyBatis三个框架的缩写,它们通常一起使用以构建企业级的Java Web应用。这三个框架分别负责不同的功能:Spring提供核心功能;SpringMVC是一个基于Java的实现了MVC设计模式的请求驱动类型的轻量级Web框架;MyBatis是一个支持定制化SQL、存储过程以及高级映射的持久层框架。Master在这里表示这是项目的主分支。这表明websocket包可能是一个SSM项目中的模块,用于提供WebSocket通讯支持,允许开发者在一个集成了SSM框架的Java Web应用中使用WebSocket技术。 综上所述,这个websocket包可以提供给开发者一种简洁有效的方式,在遵循Spring框架原则的同时,实现WebSocket通信功能。开发者可以利用此包在Eclipse等IDE中快速开发出支持实时通信的Web应用,极大地提升开发效率和应用性能。
recommend-type

电力电子技术的智能化:数据中心的智能电源管理

# 摘要 本文探讨了智能电源管理在数据中心的重要性,从电力电子技术基础到智能化电源管理系统的实施,再到技术的实践案例分析和未来展望。首先,文章介绍了电力电子技术及数据中心供电架构,并分析了其在能效提升中的应用。随后,深入讨论了智能化电源管理系统的组成、功能、监控技术以及能
recommend-type

通过spark sql读取关系型数据库mysql中的数据

Spark SQL是Apache Spark的一个模块,它允许用户在Scala、Python或SQL上下文中查询结构化数据。如果你想从MySQL关系型数据库中读取数据并处理,你可以按照以下步骤操作: 1. 首先,你需要安装`PyMySQL`库(如果使用的是Python),它是Python与MySQL交互的一个Python驱动程序。在命令行输入 `pip install PyMySQL` 来安装。 2. 在Spark环境中,导入`pyspark.sql`库,并创建一个`SparkSession`,这是Spark SQL的入口点。 ```python from pyspark.sql imp
recommend-type

新版微软inspect工具下载:32位与64位版本

根据给定文件信息,我们可以生成以下知识点: 首先,从标题和描述中,我们可以了解到新版微软inspect.exe与inspect32.exe是两个工具,它们分别对应32位和64位的系统架构。这些工具是微软官方提供的,可以用来下载获取。它们源自Windows 8的开发者工具箱,这是一个集合了多种工具以帮助开发者进行应用程序开发与调试的资源包。由于这两个工具被归类到开发者工具箱,我们可以推断,inspect.exe与inspect32.exe是用于应用程序性能检测、问题诊断和用户界面分析的工具。它们对于开发者而言非常实用,可以在开发和测试阶段对程序进行深入的分析。 接下来,从标签“inspect inspect32 spy++”中,我们可以得知inspect.exe与inspect32.exe很有可能是微软Spy++工具的更新版或者是有类似功能的工具。Spy++是Visual Studio集成开发环境(IDE)的一个组件,专门用于Windows应用程序。它允许开发者观察并调试与Windows图形用户界面(GUI)相关的各种细节,包括窗口、控件以及它们之间的消息传递。使用Spy++,开发者可以查看窗口的句柄和类信息、消息流以及子窗口结构。新版inspect工具可能继承了Spy++的所有功能,并可能增加了新功能或改进,以适应新的开发需求和技术。 最后,由于文件名称列表仅提供了“ed5fa992d2624d94ac0eb42ee46db327”,没有提供具体的文件名或扩展名,我们无法从这个文件名直接推断出具体的文件内容或功能。这串看似随机的字符可能代表了文件的哈希值或是文件存储路径的一部分,但这需要更多的上下文信息来确定。 综上所述,新版的inspect.exe与inspect32.exe是微软提供的开发者工具,与Spy++有类似功能,可以用于程序界面分析、问题诊断等。它们是专门为32位和64位系统架构设计的,方便开发者在开发过程中对应用程序进行深入的调试和优化。同时,使用这些工具可以提高开发效率,确保软件质量。由于这些工具来自Windows 8的开发者工具箱,它们可能在兼容性、效率和用户体验上都经过了优化,能够为Windows应用的开发和调试提供更加专业和便捷的解决方案。
recommend-type

如何运用电力电子技术实现IT设备的能耗监控

# 摘要 随着信息技术的快速发展,IT设备能耗监控已成为提升能效和减少环境影响的关键环节。本文首先概述了电力电子技术与IT设备能耗监控的重要性,随后深入探讨了电力电子技术的基础原理及其在能耗监控中的应用。文章详细分析了IT设备能耗监控的理论框架、实践操作以及创新技术的应用,并通过节能改造案例展示了监控系统构建和实施的成效。最后,本文展望了未来能耗监控技术的发展趋势,同时