冉冉說(shuō)
2019-10-12 13:52:06
我的Web應(yīng)用程序存在一個(gè)小問(wèn)題:一個(gè)與spring boot API連接的angular2應(yīng)用程序。我無(wú)法從angular2應(yīng)用訪問(wèn)我的請(qǐng)求。我收到此錯(cuò)誤: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);}為了解決該問(wèn)題,我在控制器類中添加了@CrossOrigin。它解決了getAll方法的問(wèn)題,但沒(méi)有解決其他方法的問(wèn)題。如何解決它,以便我可以使用PUT方法而不會(huì)出現(xiàn)此錯(cuò)誤?
3 回答

犯罪嫌疑人X
TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
@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;
}
添加回答
舉報(bào)
0/150
提交
取消