No 'Access-Control-Allow-Origin' header is present on the requested resource.
遇到了一个CORS的问题。前端运行在localhost:5173,后端在localhost:8080,调用API的时候被浏览器拦截了,提示没有Access-Control-Allow-Origin头。CORS是浏览器的一种安全机制,防止跨域请求,除非服务器明确允许。
要解决CORS问题,可以通过以下两种方法实现:
方法一:配置前端代理(推荐用于开发环境)
修改Vite配置文件 (vite.config.js):
点击查看代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
点击查看代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}
浙公网安备 33010602011771号