为什么服务器响应状态为 415 - API Post 方法

Why did the server respond with a status of 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);
    }

当涉及到 posting 到 "localhost:port/CityInfo" 时,postman 与 {"id":"1","name":"London"} 并在“/CityInfo”中读取。

当我尝试 post 使用 JS 时,它 returns 错误 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();

在控制台上返回: "Failed to load resource: the server responded with a status of 415 ()"

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

任何帮助都是 great.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()

它returns: POST http://localhost:8084/CityInfo 415

documentation here 解释了 415 响应的含义。

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

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

所以基本上我发送的 JSON 文档格式错误。 使用 Postman 时,它有 'Content-Type': 'application/json'

这是编辑后的JS:

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