我正在尝试使用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;
}
.
.
.
}
The Rest Controller:
@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
documentation here解释415响应的含义。
很可能您的postData函数中的Content-Type或Content-Encoding错误。
无论如何,您需要检查端点期望什么,并确保您的请求符合那些期望。