课次32:CORS跨域配置
一、教学目标
后端配置CORS,允许前端http://localhost:5173访问。
前端配置代理(已在第二阶段完成,此处仅确认)。
二 、核心知识点(简要)
CORS:跨域资源共享,通过响应头Access-Control-Allow-Origin允许跨域请求。
三、操作步骤
- 在后端工程中的InterceptorConfig中添加CORS配置
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
添加位置如下:
报红,就选导入类。
- 前端配置
vite.config.js代理配置:
export default defineConfig({
plugins: [vue()],
server: {
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, '') // 去掉 /api 前缀(如果你后端接口没有 /api 前缀)
}
}
}
})
更改位置:
request.js中baseURL设为/api。
- 再运行前后端工程,登录测试
先删除这一行,再运行后端工程➡️前端工程➡️登录账号密码➡️看是否登录成功。
课次32:CORS跨域配置
一、教学目标
二 、核心知识点(简要)
三、操作步骤
1. 在后端工程中的InterceptorConfig中添加CORS配置
2. 前端配置
3. 再运行前后端工程,登录测试
EOF
浙公网安备 33010602011771号