You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中获取Spring Boot接口返回的Location Header并发起后续请求

你之所以拿不到Location响应头,是跨域场景下的默认安全限制导致的:CORS 规范默认仅允许前端 JavaScript 访问以下7种简单响应头:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma,Location 不在默认暴露列表中,所以即使服务端实际返回了该响应头,前端也无法直接读取。

解决方案分两步配置即可


第一步:Spring Boot 后端配置

你需要在跨域配置中显式声明暴露 Location 响应头,两种常用配置方式:

方式1:单个接口/Controller 配置

直接在对应的 Controller 类或者接口方法上添加 @CrossOrigin 注解,指定暴露的头:

@CrossOrigin(exposedHeaders = "Location")
@RestController
@RequestMapping("/authors")
public class AuthorController {
    // 你的接口方法
    @PostMapping
    ResponseEntity<Author> createAuthor(@RequestBody Author author) {
        var result = repository.save(author); //JpaRepository
        return ResponseEntity.created(URI.create("/" + result.getAuthorId())).body(result);
    }
}
方式2:全局跨域配置

如果需要全局生效,可以新增跨域配置类:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000") // 换成你的React前端实际地址
                .allowedMethods("*")
                .allowedHeaders("*")
                .exposedHeaders("Location") // 关键配置:暴露Location头给前端
                .allowCredentials(true);
    }
}

为了后续使用更方便,建议服务端返回的 Location 直接使用完整绝对路径,不需要前端手动拼接域名,修改返回逻辑即可,也可以通过Servlet上下文动态获取域名避免硬编码:

return ResponseEntity.created(URI.create("http://localhost:8080/" + result.getAuthorId())).body(result);

第二步:前端 fetch 代码调整

配置完成后,你就可以在 fetch 的响应对象中通过 headers.get('Location') 获取该地址,后续发起 PUT 请求上传文件即可,示例代码:

fetch(`http://localhost:8080/authors`, {
    method: 'post',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        // 你的请求体参数
    })
}).then(r => {
    // 获取Location头对应的资源地址
    const resourceUrl = r.headers.get('Location');
    // 如果服务端返回的是相对路径,手动拼接服务端域名前缀即可:
    // const resourceUrl = `http://localhost:8080${r.headers.get('Location')}`;
    
    // 后续发起PUT请求上传文件
    const uploadFile = // 你要上传的文件对象
    return fetch(resourceUrl, {
        method: 'PUT',
        body: uploadFile
    })
}).then(putRes => {
    console.log('文件上传完成', putRes)
}).catch(err => {
    console.error('操作失败', err)
})

内容的提问来源于stack exchange,提问作者Monoxyd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:18:05