疑难杂症:postman测试通过,但axios还是报跨域问题
问题调用接口报错误:Access to XMLHttpRequest at 'http://xxxx/api/Order/OrderList' from origin 'http://xxx.xx.xx.xx:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on th
问题
调用接口报错误:
Access to XMLHttpRequest at ‘http://xxxx/api/Order/OrderList’ from origin ‘http://xxx.xx.xx.xx:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
分析
看到上面的问题,第一反应就是跨域问题。处理方法,要么后台处理跨域,要么使用代理跨域,so eary。
方法一: 后台进行跨域处理,处理后,postman测试没有问题,有些电脑访问没有问题,但是个别电脑访问,就会出现上面的跨域问题提示,到底是什么原因呢?
方法二:使用代理跨域没有问题.
原因
最后,终于找到了原因,后台处理跨域时,Access-Control-Allow-Origin设置为号,而号,在处理origin为null的情况下,就有问题,没有生效。
解决方案(后端处理)
针对origin为null的情况,单独处理一下
代码如下:
String origin = httpServletRequest.getHeader("Origin");
if (origin == null) {
httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
} else {
httpServletResponse.addHeader("Access-Control-Allow-Origin", origin);
}
注:
在发起post请求时,代码不止发一次,会先发一个options请求,所以,注意不要重复添加,否则也不能解决问题。
String origin = httpServletRequest.getHeader("Origin");
if (origin == null) {
httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
} else if (httpServletRequest.getMethod().equals("OPTIONS")) {
httpServletResponse.addHeader("Access-Control-Allow-Origin", origin);
}
总结
虽说,这问题,应该有后端来解决,但是由于这个问题,只是特定情况下才会出现的,所以容易扯不清,so , 我们前端,也要记住这个问题,如何出现这个问题,也可以提醒后端,可能是这个原因。
作者:doubleyong
公众号:bug收集
博客:bugshouji.com (专门解决与收集bug的网站)
更多推荐
所有评论(0)