为了账号安全,请及时绑定邮箱和手机立即绑定

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条经验 获得超7个赞

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


@CrossOrigin(origins = "*")


查看完整回答
反对 回复 2019-10-12
  • 3 回答
  • 0 关注
  • 518 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信