首页 > 解决方案 > 为什么服务器响应状态为 415 - API Post Method

问题描述

我正在尝试使用 Spring Boot 创建我自己的 API,它现在使用从空气质量 API 访问外部数据。

我有一个 CityInfo 实体:

@Entity
public class CityInfo{
    @Id
    private String id;
    private String name;


    public CityInfo(){

    }

    public CityInfo(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
.
.
.
}

休息控制器:

    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private CityInfoRepository cityInfoRepository;

    @GetMapping("/CityInfo")
    public List<CityInfo> getAllCityInfo() {
        return cityInfoRepository.findAll();
    }

    @PostMapping ("/CityInfo")
    public void addCityInfo(@RequestBody CityInfo cityInfo) {
        cityInfoService.add(cityInfo);
    }

在发布到“localhost:port/CityInfo”时,邮递员使用 {"id":"1","name":"London"} 可以正常工作,并且可以在“/CityInfo”中读取。

当我尝试使用 JS 发布时,它返回错误 415,据说是“415 不支持的媒体类型”。

function postData(){
    let id = "31";
    let name = "CITYCITY"
    fetch('http://localhost:8084/CityInfo', {
        method: 'POST',
        body:JSON.stringify({"id":id,
                            "name":name})
    }).then((res) => res.text())
        .then((text)=>console.log("text:"+ text))
        .catch((err)=>console.log("err:" + err))
}
postData();

在控制台上返回:“加载资源失败:服务器响应状态为 415 ()”

我想我发送的 JSON 格式错误,但至少在我看来并没有。

任何帮助都会很棒。 Ty

编辑:邮递员照片 在此处输入图像描述

function postData(){
    let id = "31";
    let name = "CITYCITY"
    fetch('http://localhost:8084/CityInfo', {
        method: 'POST',
        body:JSON.stringify({"id":id,
                            "name":name}),
        contentType: 'application/json',
        contentEncoding: 'gzip',
        contentEncoding: 'deflate',
        contentEncoding: 'br',
    }).then((res) => res.text())
        .then((text)=>console.log("text:"+ text))
        .catch((err)=>console.log("err:" + err))
}
postData()

它返回: POST http://localhost:8084/CityInfo 415

标签: javascriptapispring-restcontroller

解决方案


此处的文档解释了 415 响应的含义。

您的 postData 函数中的 Content-Type 或 Content-Encoding 可能是错误的。

无论如何,您需要检查端点的期望并确保您的请求符合这些期望。


推荐阅读