在尝试从一个web前端使用HTTP Request请求访问REST服务端时,遇到错误: XMLHttpRequest cannot load http://localhost:8080/ping. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
补充:
我服务端java(在eclipse里跑) 传一个图片(服务器路径)给webstorm 然而image访问的是webstorm下的project的资源 而不是Tomcat下的资源。。。
如果我没理解错你的意思的话,应该是 webstorm 作为服务器。如果反了也是类似只不过要写 jsp 的代码。
HTML5 解决跨域的问题是使用 HTTP 头的。
所以图片不能直接通过服务器传输,而是需要使用 PHP处理,获知直接修改服务器的配置文件:
<?php
header('Content-type: image/jpeg');
header('Access-Control-Allow-Origin:*');
echo file_get_contents("path/to/image.jpg");
?>
调试时修改Access-Control-Allow-Origin值为*,正式上线再调成默认值。
补充
1. 代码解决- jsonp请求
jsonp 的概念等建议自行查找
大概阅读
用jQuery与JSONP轻松解决跨域访问的问题
2. 浏览器调试解决 - 命令关闭Chrome的跨域限制
Windows下
关闭所有打开的Chrome。(重要)。否则,将没有效果!
-
创建Chrome的快捷方式,修改快捷方式的目标为:
"C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security
3、双击我们创建的Chrome快捷方式,打开Chrome,如图出现“您使用的是不受支持的命令行标记:--disable-web-security。稳定性和安全性会有所下降”,表示你取消了跨域限制了,可以随意跨域调用数据了
Mac OS (命令行执行)
彻底关闭chrome为前提
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security
或者
open -a "Google Chrome" --args --disable-web-security
Linux
chromium-browser --disable-web-security
相关参考及详细说明
Chrome 浏览器跨域和安全访问问题 使用 chrome的命令行标记:disable-web-security 参数联调线上数据
nginx启动代理 然后配置好跨域 你的所有连接指向nginx服务器 nginx服务器代理你的请求到web service 就是这么easy