* Opera 不支持
2.3.2 测试
测试页面http://localhost:8080/test3.html使用jquery发送Ajax请求。
<html>
<head><title>testing cross sop</title></head>
<body>
Testing.
<script src="jquery-2.0.0.min.js"></script>
<script type='text/javascript'>
$.ajax({
url: 'http://localhost:8000/hello',
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
</script>
</body>
</html>
测试Restful API(http://localhost:8000/hello/{name})使用bottle.py来host。
from bottle import route, run, response
@route('/hello')
def index():
return 'Hello World.'
run(host='localhost', port=8000)
测试1:
测试正常的跨域请求的行为。
测试结果:
1. 跨域GET请求已经发出,请求header中带有
Origin http://localhost:8080
2. 服务器端正确给出response
3. Javascript拒绝读取数据,在firebug中发现reponse为空,并且触发error回调
测试2:
测试支持CORS的服务器的跨域请求行为。
对Restful API做如下改动,在response中加入header:
def index():
#Add CORS header#
response.set_header("Access-Control-Allow-Origin", "http://localhost:8080")
return 'Hello World.'
测试结果:
1. 跨域GET请求已经发出,请求header中带有
Origin http://localhost:8080
2. 服务器端正确给出response
3. 客户端正常获取数据
测试3:
测试OPTIONS请求获取CORS信息。
对客户端的Ajax请求增加header:
$.ajax({
url: 'http://localhost:8000/hello',
headers: {'Content-Type': 'text/html'},
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
对Restful API做如下改动:
@route('/hello', method = ['OPTIONS', 'GET'])
def index():
if request.method == 'OPTIONS':
return ''
return 'Hello World.'
测试结果:
1. Ajax函数会首先发送OPTIONS请求
2. 针对OPTIONS请求服务器
3. 客户端发现没有CORS header后不会发送GET请求
测试4:
增加服务器端对OPTIONS方法的处理。
对Restful API做如下改动:
@route('/hello', method = ['OPTIONS', 'GET'])
def index():
response.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'
response.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type'
if request.method == 'OPTIONS':
return ''
return 'Hello World.'
内容版权声明:除非注明,否则皆为本站原创文章。
