我的Web應用程序存在一個小問題:一個與spring boot API連接的angular2應用程序。我無法從angular2應用訪問我的請求。我收到此錯誤:Failed to load http://localhost:8080/deliveryMan/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.Java代碼:@RestController@RequestMapping(value = "/deliveryMan")@CrossOriginpublic class DeliveryManController { @Autowired DeliveryManService deliveryManService; @RequestMapping(value = "/getAllDeliveryMan", method = RequestMethod.GET) public Iterable<DeliveryMan> getAllDeliveryMan(){ return deliveryManService.findAll(); } @RequestMapping(method = RequestMethod.PUT, consumes = "application/json") public DeliveryMan addDeliveryMan(@RequestBody DeliveryMan deliveryMan) throws InvalidObjectException { deliveryManService.save(deliveryMan); return deliveryMan; }@SpringBootApplication@EnableAutoConfiguration@ComponentScanpublic class MyApp{ public static void main(String[] args) { SpringApplication.run(MyApp.class, args); }}angular2代碼:private apiUrl = 'http://localhost:8080/deliveryMan/';getAll(): Promise<DeliveryMan[]> { const url = this.apiUrl + 'getAllDeliveryMan'; return this.http.get(url) .toPromise() .then(response => response.json().data as DeliveryMan[]) .catch(this.handleError);}saveDeliveryMan(deliveryMan: DeliveryMan): Promise<DeliveryMan> { const url = this.apiUrl; return this.http.put(url, JSON.stringify(deliveryMan), this.headers) .toPromise() .then(() => deliveryMan) .catch(this.handleError);}為了解決該問題,我在控制器類中添加了@CrossOrigin。它解決了getAll方法的問題,但沒有解決其他方法的問題。如何解決它,以便我可以使用PUT方法而不會出現(xiàn)此錯誤?
3 回答

九州編程
TA貢獻1785條經(jīng)驗 獲得超4個贊
@CrossOrigin(origins = "http://localhost:4200")向您的控制器添加注釋,例如:
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(method = RequestMethod.PUT, consumes = "application/json")
public DeliveryMan addDeliveryMan(@RequestBody DeliveryMan deliveryMan) throws InvalidObjectException {
deliveryManService.save(deliveryMan);
return deliveryMan;
}
添加回答
舉報
0/150
提交
取消