javascript – Angular2 / Spring Boot允许PUT上的Cross Origin

我的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")
@CrossOrigin
public 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
@ComponentScan
public 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方法而不会出现此错误

解决方法:

在项目中创建CORSFilter.java文件.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    /**
     * CORS filter for http-request and response
     */
    public CORSFilter() {
    }

    /**
     * Do Filter on every http-request.
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, servletexception {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");

        if ("OPTIONS".equalsIgnoreCase(request.getmethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    /**
     * Destroy method
     */
    @Override
    public void destroy() {
    }

    /**
     * Initialize CORS filter 
     */
    @Override
    public void init(FilterConfig arg0) throws servletexception {
    }
}

你可以参考这篇文章Angular 2 Spring Boot Login CORS Problems

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...