【发布时间】:2020-07-26 18:56:33
【问题描述】:
我正在尝试使用 Spring Boot 创建自己的 API,该 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()
它返回: 发布http://localhost:8084/CityInfo415
【问题讨论】:
标签: javascript api spring-restcontroller