javascript - 为什么服务器响应状态为 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
解决方案
此处的文档解释了 415 响应的含义。
您的 postData 函数中的 Content-Type 或 Content-Encoding 可能是错误的。
无论如何,您需要检查端点的期望并确保您的请求符合这些期望。
推荐阅读
- javascript - 如何将 _app.js 包装在多个提供程序中?
- python - 如何在 Python 上使用 webbot 浏览器一次按下多个键
- javascript - 如何将所有数据提取到拆分行中的雪花对象数组中?
- android - ActivityResultContracts.TakeVideo() 在录制视频后返回 NULL。但该视频确实存在于 Movies 文件夹中
- c# - 由于 IL2CPP,Unity 无法构建
- reactjs - 如何在 React 中更改 svg 样式图标的颜色?
- postgresql - 如何使用 INSERT 规则返回值创建视图 - 规则定义中没有 INSERT
- angular - ANGULAR 10 Keycloak 被 CORS 策略阻止
- javascript - 使 DIV 占用另一个隐藏的 DIV 的空间
- python - 测试 GPU 是否可用于 tensorflow