Restlet解决AJAX跨域问题

在前端用JavaScript AJAX直接调用Restlet框架写的一个REST接口时,遇到了传说中的AJAX跨域问题。

百度谷歌了很久,看到了很多人把JavaScript的dataType改成jsonp以规避这个问题(参考:http://www.cnblogs.com/sunxucool/p/3433992.html),然而,这样处理会增加JavaScript的调用复杂度,不利于项目代码的维护。

在查看Restlet官方文档后,发现其框架中已加入了CorsService来解决AJAX跨域问题。

更新至Restlet 2.3.7版本,在main方法中加入CorsService设置,具体如下:

Component component = new Component();
component.getServers().add(Protocol.HTTP, 8082);
component.getServers().getContext().getParameters().add("maxThreads", "512");
// 解决AJAX跨域问题
CorsService cors = new CorsService();
cors.setAllowedOrigins(new HashSet(Arrays.asList("*")));
cors.setAllowedCredentials(true);
component.getServices().add(cors);
// 增加Applications
component.getDefaultHost().attach("/api", new PathApplication());
// 启动
component.start();

重启REST服务,重新进行AJAX请求数据,顺利获取到,问题解决!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值