I'm building a web application using Spring Boot and Angular JS which will perform CRUD operations. I have successfully created one class and when implementing this class I'm getting this error "Request method 'POST' not supported"
My controller class is:
package com.fyp.controller;
import com.fyp.masterdata.Truck;
import com.fyp.masterdata.TruckRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class TruckController {
@Autowired
TruckRepository truckRepository;
@GetMapping(value="/truck", produces= MediaType.APPLICATION_JSON_VALUE)
public List<Truck> getAll1() {
List<Truck> list = new ArrayList<>();
Iterable<Truck> truck = truckRepository.findAll();
truck.forEach(list::add);
return list;
}
@PostMapping(value="/posttruck")
public Truck postTruck(@RequestBody Truck truck) {
truckRepository.save(new Truck(truck.getName(), truck.getCapacity()));
return truck;
}
@GetMapping(value="/getTruckByName/{name}", produces= MediaType.APPLICATION_JSON_VALUE)
public List<Truck> getTruckByName(@PathVariable String name) {
List<Truck> truck = truckRepository.getTruckByName(name);
return truck;
}
@DeleteMapping(value="/truck/{id}")
public void deleteTruck(@PathVariable long id){
truckRepository.delete(id);
}
}
This is the error which I'm getting when I hit the above URL with POST request.
>#2018-05-11 18:42:46.868 WARN 10596 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
This is my front-end Angular JS code which is used to hit the URL. I'm running http://localhost:4200/truck and trying to get it work.
// Get all trucks
getTruck(): Promise<Truck[]> {
return this.http.get(this.truckUrl)
.toPromise()
.then(response => response.json() as Truck[])
.catch(this.handleError);
}
getTruckByName(name: string): Promise<Truck[]> {
const url = `/findbytruck/${name}`;
return this.http.get(url)
.toPromise()
.then(response => response.json() as Truck)
.catch(this.handleError);
}
create1(truck: Truck): Promise<Truck> {
return this.http
.post("truck", JSON.stringify(truck), {headers : this.headers})
.toPromise()
.then(res => res.json() as Truck)
.catch(this.handleError);
}
delete1(id: number): Promise<void> {
const url = `${this.truckUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
Thank You.
post("posttruck", JSON.stringify(truck), {headers : this.headers}). - Arnaud