前端采用vue,后端采用springboot+微服务+网关,进行对接时出现以下报错怎么解决Access to XMLHttpRequest at 'http://127.0.0.1:8090/user/admin/register' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
时间: 2024-04-09 08:31:14 浏览: 138
前端采用vue,后端采用springboot,基于知识图谱构建的中文病症问答系统,可用于个人学习研究,毕业设计,课程设计
在Vue前端和Spring Boot后端中解决CORS问题,你可以尝试以下方法:
1. 后端配置CORS过滤器:在Spring Boot后端的网关服务中,添加一个CORS过滤器,处理跨域请求。你可以创建一个类实现`javax.servlet.Filter`接口,然后在`doFilter()`方法中设置响应头,包括`Access-Control-Allow-Origin`字段。示例代码如下:
```java
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
httpResponse.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}
}
```
2. 配置Spring Security:如果你在后端使用了Spring Security来进行身份验证和授权,你可以在配置类中添加以下代码来解决CORS问题:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "X-Requested-With"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
```
这样配置后,Spring Security将允许来自任何源的跨域请求。
3. 使用代理:在开发环境下,你可以在Vue的配置文件中设置代理,将前端请求转发到后端服务,从而避免浏览器的CORS限制。在`vue.config.js`文件中添加以下代码:
```javascript
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8090', // 后端服务地址
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
```
然后,在前端代码中使用`/api`作为请求的基础路径,例如:`axios.post('/api/user/admin/register', data)`。
这些方法中的任何一种都可以帮助你解决CORS问题。你可以根据你的具体情况选择适合的方法。
阅读全文