我正在使用Spring Boot和Angular JS构建一个Web应用程序,它将执行CRUD操作。我已成功创建了一个类,并且在实现此类时,我收到此错误“请求方法'POST'不受支持”
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);
}
}
这是我在使用POST请求点击上述网址时遇到的错误。
>#2018-05-11 18:42:46.868 WARN 10596 --- [nio-8080-exec-3] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
这是我用于点击URL的前端Angular JS代码。我正在运行http://localhost:4200/truck并试图让它发挥作用。
// 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.
答案 0 :(得分:0)
也许你可以改变
@GetMapping(value="/truck", produces= MediaType.APPLICATION_JSON_VALUE)
至
@PostMapping(value="/truck", produces= MediaType.APPLICATION_JSON_VALUE)
要么
@RequestMapping(value = "/truck", method = { RequestMethod.POST, RequestMethod.GET })