服务器为什么以状态415-API Post Method响应

问题描述 投票:1回答:2

我正在尝试使用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”:“伦敦”},并且在“ / 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

编辑:邮递员照片enter image description here

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()

它返回:POSThttp://localhost:8084/CityInfo415

javascript api spring-restcontroller
2个回答
0
投票

documentation here解释415响应的含义。

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

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


0
投票

所以基本上我发送的是格式错误的JSON文档。使用邮递员时,其具有“内容类型”:“ 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()
© www.soinside.com 2019 - 2024. All rights reserved.