feat(API): 修改文章ID类型为String并添加CORS配置

将文章ID从Integer类型改为String类型以支持更灵活的ID格式
添加CORS配置类解决跨域问题,允许所有来源访问API
This commit is contained in:
qingfeng1121
2025-10-11 13:32:41 +08:00
parent 470cf71713
commit 299c9a57ec
6 changed files with 996 additions and 5 deletions

View File

@@ -0,0 +1,50 @@
package com.qf.myafterprojecy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* CORS配置类用于解决跨域问题
*/
@Configuration
public class CorsConfig {
/**
* 创建CORS过滤器配置跨域请求的规则
*/
@Bean
public CorsFilter corsFilter() {
// 创建CORS配置对象
CorsConfiguration config = new CorsConfiguration();
// 允许的来源,这里允许所有来源,实际生产环境应该限制特定域名
config.addAllowedOriginPattern("*");
// 允许携带凭证如Cookie
config.setAllowCredentials(true);
// 允许的请求方法
config.addAllowedMethod("*");
// 允许的请求头
config.addAllowedHeader("*");
// 暴露的响应头这些头信息可以被前端JavaScript访问
config.addExposedHeader("*");
// 设置预检请求的有效期(秒)
config.setMaxAge(3600L);
// 创建基于URL的CORS配置源
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 为所有路径应用CORS配置
source.registerCorsConfiguration("/**", config);
// 返回配置好的CORS过滤器
return new CorsFilter(source);
}
}

View File

@@ -30,9 +30,8 @@ public class ArticleController {
* @return 返回包含文章信息的ResponseMessage对象
*/
@GetMapping("/{id}")
public ResponseMessage<Article> getArticle(@PathVariable Integer id) {
public ResponseMessage<Article> getArticle(@PathVariable String id) {
return articleService.getArticleById(id);
}
/**

View File

@@ -25,9 +25,12 @@ public class ArticleService implements IArticleService {
@Override
@Transactional(readOnly = true)
public ResponseMessage<Article> getArticleById(Integer id) {
public ResponseMessage<Article> getArticleById(String id) {
try {
Article article = articleRepository.findById(id)
if (id == null || id.isEmpty()) {
return ResponseMessage.failure("文章ID不能为空");
}
Article article = articleRepository.findById(Integer.parseInt(id))
.orElseThrow(() -> new RuntimeException("文章不存在"));
// 暂时不增加浏览次数,以避免事务问题

View File

@@ -7,7 +7,7 @@ import com.qf.myafterprojecy.pojo.dto.ArticleDto;
import java.util.List;
public interface IArticleService {
ResponseMessage<Article> getArticleById(Integer id);
ResponseMessage<Article> getArticleById(String id);
ResponseMessage<List<Article>> getAllArticles();
ResponseMessage<Article> saveArticle(ArticleDto articleDto);
ResponseMessage<Article> updateArticle(Integer id, ArticleDto articleDto);