feat(config): 添加 CORS 配置支持跨域请求

- 新增 CorsConfig 类实现 WebMvcConfigurer 接口
- 配置允许所有域名、方法和请求头的跨域访问- 支持发送 Cookie 凭证信息- 设置预检请求有效期为 1 小时

fix(controller): 修正流式响应的内容类型- 将 OpenAIController 的 generateStream 接口返回类型改为 TEXT_EVENT_STREAM_VALUE
- 使用 MediaType.TEXT_EVENT_STREAM_VALUE 替代硬编码字符串
- 确保服务端推送事件(SSE)能正确被客户端接收
This commit is contained in:
hanserwei
2025-10-22 14:05:31 +08:00
parent bfbfdbc90d
commit 0782148820
2 changed files with 21 additions and 1 deletions

View File

@@ -0,0 +1,19 @@
package com.hanserwei.airobot.config;
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("/**") // 匹配所有路径
.allowedOriginPatterns("*") // 允许所有域名(生产环境应指定具体域名)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法
.allowedHeaders("*") // 允许所有请求头
.allowCredentials(true) // 允许发送 Cookie
.maxAge(3600); // 预检请求的有效期(秒)
}
}

View File

@@ -5,6 +5,7 @@ import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.Generation; import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel; import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@@ -36,7 +37,7 @@ public class OpenAIController {
* @param message 对话输入内容 * @param message 对话输入内容
* @return 对话结果 * @return 对话结果
*/ */
@GetMapping(value = "/generateStream", produces = "text/html;charset=utf-8") @GetMapping(value = "/generateStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> generateStream(@RequestParam(value = "message", defaultValue = "你是谁?") String message) { public Flux<String> generateStream(@RequestParam(value = "message", defaultValue = "你是谁?") String message) {
// 构建提示词 // 构建提示词
Prompt prompt = new Prompt(new UserMessage(message)); Prompt prompt = new Prompt(new UserMessage(message));