【发布时间】:2013-09-19 03:56:48
【问题描述】:
我们在 web2py 上的 restfull web 服务中的跨域资源共享 (CORS) 实施遇到了一些问题。
我们尝试在 web2py 的服务器端实现 CORS,如下所示:(https://groups.google.com/forum/#!msg/web2py/kSUtyNcUQGI/qfiIqfUiWLwJ)
我们在 models/0.py 中添加了以下内容,(在控制器中实际的 restfull api 处理程序之前更新响应头)
=================================
if request.env.http_origin:
response.headers['Access-Control-Allow-Origin'] = request.env.http_origin
response.headers['Access-Control-Allow-Origin'] = "*"
response.headers['Access-Control-Allow-Credentials'] = 'true'
response.headers['Access-Control-Max-Age'] = 86400
if request.env.request_method == 'OPTIONS':
if request.env.http_access_control_request_method:
print request.env.http_access_control_request_method
response.headers['Access-Control-Allow-Methods'] = request.env.http_access_control_request_method
if request.env.http_access_control_request_headers:
response.headers['Access-Control-Allow-Headers'] = request.env.http_access_control_request_headers
===========================
RESTful POST & GET 现在可以工作了 但 PUT 和 DELETE 不是因为预检 http OPTIONS 请求被 web2py 拒绝为“400 BAD REQUEST”
例如,当使用本地网页的 ajax 调用调用 restful webservice 时, 我们在 NetBeans 日志中收到以下错误消息。
加载资源失败:服务器响应状态为 400 (错误请求)(10:46:36:182 | 错误,网络)在 127.0.0.1:8000/test/default/api/entries/2.json 加载资源失败:Origin localhost:8383 is not allowed by 访问控制允许来源。 (10:46:36:183 | 错误,网络)在 127.0.0.1:8000/test/default /api/entries/2.json XMLHttpRequest 无法加载 127.0.0.1:8000/test/default /api/entries/2.json。起源 Access-Control-Allow-Origin 不允许 localhost:8383。 (10:46:36:183 | 错误,javascript)在 www/page/test.html
【问题讨论】: