NutzCN Logo
问答 ajax post 请求json跨域怎么解决
发布于 2360天前 作者 qq_9f4a6570 2220 次浏览 复制 上一个帖子 下一个帖子
标签:

@POST
@At("/update")
@Ok("json")
@AdaptBy(type=JsonAdaptor.class)
@Filters({@By(type = CrossOriginFilter.class)})

6 回复

改成这样试试

@At(value="/batch_update", methods="options")

我自定义了一个MyCrossOriginFilter.class,并在Access-Control-Allow-Headers 额外添加了允许"token",客户端请求待遇token时有个别接口不支持跨越了,请求不带token就支持。什么原因呢?

public class MyCrossOriginFilter implements ActionFilter {
	
	private static final Log log = Logs.get();
	protected String origin;
	protected String methods;
	protected String headers;
	protected String credentials;
	
	public MyCrossOriginFilter() {
		this("*", "GET, POST, PUT, DELETE, OPTIONS, PATCH", "Origin, Content-Type, Accept, Authorization, X-Requested-With,token", "true");
	}
	
	public MyCrossOriginFilter(String origin, String methods, String headers, String credentials) {
		this.origin = origin;
		this.methods = methods;
		this.headers = headers;
		this.credentials = credentials;
	}
	
	public View match(ActionContext ac) {
		HttpServletResponse resp = ac.getResponse();
		if (!Strings.isBlank(this.origin)) {
			resp.setHeader("Access-Control-Allow-Origin", this.origin);
		}
		
		if (!Strings.isBlank(this.methods)) {
			resp.setHeader("Access-Control-Allow-Methods", this.methods);
		}
		
		if (!Strings.isBlank(this.headers)) {
			resp.setHeader("Access-Control-Allow-Headers", this.headers);
		}
		
		if (!Strings.isBlank(this.credentials)) {
			resp.setHeader("Access-Control-Allow-Credentials", this.credentials);
		}
		
		if ("OPTIONS".equals(ac.getRequest().getMethod())) {
			if (log.isDebugEnabled()) {
				log.debugf("Feedback -- [%s] [%s] [%s] [%s]", new Object[]{this.origin, this.methods, this.headers, this.credentials});
			}
			
			return new VoidView();
		}

		return null;
	}
}
@IocBean(name = "adsHome")
@Filters({ @By(type = MyActionFilter.class, args = {""})})
@At("ads/home")
public class HomeControl extends BaseController {

	@At("/campaign/list")
	@Ok("json")
	@Filters({@By(type = MyCrossOriginFilter.class)})
	public ReturnObject campaignList() {
		ReturnObject result = new ReturnObject();

		
		return result;
	}
}

另外,有另一个control 也有一个 /campaign/list 接口对这个有什么影响么?


@IocBean(name = "adsReport") @Filters({@By(type = MyActionFilter.class, args = {""})}) @At("ads/report") public class ReportControl extends BaseController { /** * 分页列表 * * @param search * @return */ @At("/campaign/list") @Ok("json") @Filters({@By(type = MyCrossOriginFilter.class), @By(type = MyActionFilter.class, args = "")}) public ReturnObject listCampaignList(@Param("..") CampaignReport search) { ReturnObject ro = new ReturnObject(); return ro; } }

映射路径是类+入口方法的@At值

路径不存在问题对吧,那跨域问题呢?很奇怪啊,为什么我把两个类里面的at地址改成不同时,跨域又没问题了,不很诡异么?

方法上的@Filters会覆盖类上的@Filters

添加回复
该帖子已被锁定,不能回复.
回到顶部