亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular2 / Spring Boot允許在PUT上交叉原點

Angular2 / Spring Boot允許在PUT上交叉原點

冉冉說 2019-10-12 13:52:06
我的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方法而不會出現此錯誤?
查看完整描述

3 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超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;

    }


查看完整回答
反對 回復 2019-10-12
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

您可以只使用:(它對所有CRUD操作都適用)


@CrossOrigin(origins = "*")


查看完整回答
反對 回復 2019-10-12
  • 3 回答
  • 0 關注
  • 607 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號