使用Ajax删除数据时Odoo后端CORS策略问题求助
解决跨域CORS问题的方案
核心问题说明
你在PHP代码里加的header('Access-Control-Allow-Origin: *')完全无效,因为前端AJAX直接请求的是Odoo后端的API地址,而非PHP页面。浏览器校验CORS规则时,只会检查Odoo返回的响应头,和PHP渲染层的设置无关。
具体修复步骤
1. 修正AJAX请求的URL参数传递
你的Odoo路由定义的是/api/delete/petty_cash/<int:id>,要求id作为路径参数,而非GET查询参数。修改AJAX代码:
$(document).on('click', '#delete_data', function(){ var id = $(this).data("id"); $.ajax({ type: 'GET', // 把id放到URL路径里,匹配Odoo的路由规则 url: `http://localhost:7073/api/delete/petty_cash/${id}`, beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "<?php echo $result->access_token;?>"); xhr.withCredentials = true; }, contentType : "application/json", // 删掉这里的data参数,因为id已经在URL里传递了 success: function() { $('.data').load("index.php"); }, error: function(response){ console.log(response.responseText); } }); });
2. 在Odoo后端添加CORS响应头
浏览器发起跨域请求前会先发OPTIONS预检请求,需要Odoo支持该方法并返回合法的CORS头。修改Odoo代码:
@http.route([ '/api/delete/petty_cash/<int:id>' ], type='http', auth="none", methods=['GET', 'OPTIONS'], csrf=False) # 新增OPTIONS方法支持 @check_valid_token def delete_petty_cash(self, id, **rec): # 处理OPTIONS预检请求 if request.httprequest.method == 'OPTIONS': # 替换成你的PHP页面实际域名(比如http://localhost:80) allowed_origin = 'http://你的前端域名' headers = { 'Access-Control-Allow-Origin': allowed_origin, 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Authorization, Content-Type', 'Access-Control-Allow-Credentials': 'true' } return request.make_response('', headers) user_id = request.uid petty_cash = request.env['petty.cash.app'].\ search([('create_uid', '=', user_id), ('id', '=', id) ]) if petty_cash: petty_cash.unlink() # 成功响应也要带CORS头 allowed_origin = 'http://你的前端域名' headers = { 'Access-Control-Allow-Origin': allowed_origin, 'Access-Control-Allow-Credentials': 'true' } # 如果你的valid_response函数支持传入headers参数,就用下面的写法 return valid_response( 200, { "msg" : "Data Deleted", }, headers=headers ) # 如果valid_response不支持headers,就替换成: # response = request.make_response(json.dumps({"msg": "Data Deleted"}), headers) # response.status_code = 200 # response.headers['Content-Type'] = 'application/json' # return response
3. 关键注意事项
- 因为你开启了
xhr.withCredentials = true,Access-Control-Allow-Origin不能用*,必须指定具体的前端域名(比如你的PHP页面运行在http://localhost就写这个地址)。 - 确保Odoo的路由明确允许
OPTIONS方法,否则预检请求会直接失败。 - 检查
Authorization头是否被允许:在Access-Control-Allow-Headers里必须包含Authorization,否则浏览器会拦截带该头的请求。
内容的提问来源于stack exchange,提问作者Bimo Anugrah Prasetyo
相关产品推荐
相关产品推荐

