I'm currently working on developing my own API using Spring Boot. Right now, it's set up to access external data from an air quality API.
Here is the CityInfo entity I have created:
@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 for handling CityInfo:
@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);
}
When making a POST request to "localhost:port/CityInfo" using Postman with {"id":"1","name":"London"}, everything works smoothly and the data is read in "/CityInfo".
However, when attempting to post data using JavaScript, I encounter Error 415 which indicates "415 Unsupported Media Type".
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();
Upon checking the console, I see the following message: "Failed to load resource: the server responded with a status of 415 ()"
I suspect that the issue lies in the format of the JSON being sent, but I can't pinpoint the exact problem.
Any assistance would be greatly appreciated. Thank you.
Edit: Screenshot from Postman https://i.sstatic.net/JR3ej.png
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()
Result: POST http://localhost:8084/CityInfo 415