允许跨域资源共享策略

huangapple go评论67阅读模式
英文:

allow CORS policy

问题

我想通过Ajax删除数据,我使用PHP渲染界面和Odoo作为后端服务,我正在使用CURL获取API,但我在CORS策略上遇到问题,就像这样点击这里查看图片

这是我的Ajax代码:

$(document).on('click', '#delete_data', function(){    
    var id = $(this).data("id"); 
    $.ajax({
        type: 'GET',
        url: "http://localhost:7073/api/delete/petty_cash/",
        beforeSend: function(xhr) {          
            xhr.setRequestHeader("Authorization", "<?php echo $result->access_token;?>");     
            xhr.withCredentials = true; 
        }, 
        contentType : "application/json",
        data: {id:id},       
        success: function() {
            $('.data').load("index.php");
        }, error: function(response){
            console.log(response.responseText);
        }
    });
});

这是我的按钮HTML代码:

<button class="btn btn-sm btn-danger btn-sm" id="delete_data" data-id='<?php echo $val['id'];?>'><i class="fa fa-trash"></i>Delete</button>

这是我的后端代码:

@http.route([
    '/api/delete/petty_cash/<int:id>'
], type='http', auth="none", methods=['GET'], csrf=False)
@check_valid_token
def delete_petty_cash(self, id, **rec):
    user_id = request.uid
    petty_cash = request.env['petty.cash.app'].\
        search([('create_uid', '=', user_id), ('id', '=', id)])
    if petty_cash:
        petty_cash.unlink()
    return valid_response(
        200, {
            "msg" : "Data Deleted",
        }
    )

我正在使用Odoo作为后端,我已经在我的PHP代码中添加了以下代码:

<?php
header('Access-Control-Allow-Origin: *');
?>

但仍然不允许CORS,如何修复这个问题?

英文:

i want to delete data via ajax, i use PHP for render interface and odoo fro backend service, i am using CURL for get API, but i have problem in CORS policy like thisenter image description here

this is my , ajax code

$(document).on(&#39;click&#39;, &#39;#delete_data&#39;, function(){    
var id = $(this).data(&quot;id&quot;); 
$.ajax({
    type: &#39;GET&#39;,
    url: &quot;http://localhost:7073/api/delete/petty_cash/&quot;,
    beforeSend: function(xhr) {          
        xhr.setRequestHeader(&quot;Authorization&quot;,   + &quot;&lt;?php echo $result-&gt;access_token;?&gt;&quot;);     
        xhr.withCredentials = true; 
    }, 
     contentType : &quot;application/json&quot;,
    data: {id:id},       
    success: function() {
        $(&#39;.data&#39;).load(&quot;index.php&quot;);
    }, error: function(response){
        console.log(response.responseText);
    }
});

});

and this is my button html code:

    &lt;button class=&quot;btn btn-sm btn-danger btn-sm&quot; id=&quot;delete_data&quot; data-id=&#39;&lt;?php echo $val[&#39;id&#39;] ?&gt;&#39;&gt;&lt;i class=&quot;fa fa-trash&quot;&gt;&lt;/i&gt;Delete&lt;/button&gt;

this is my backend code

    @http.route([
    &#39;/api/delete/petty_cash/&lt;int:id&gt;&#39;
], type=&#39;http&#39;, auth=&quot;none&quot;, methods=[&#39;GET&#39;], csrf=False)
@check_valid_token
def delete_petty_cash(self, id, **rec):
    user_id = request.uid
    petty_cash = request.env[&#39;petty.cash.app&#39;].\
        search([(&#39;create_uid&#39;, &#39;=&#39;, user_id),
                (&#39;id&#39;, &#39;=&#39;, id)
                ])
    if petty_cash:
        petty_cash.unlink()
    return valid_response(
        200, {
            &quot;msg&quot; : &quot;Data Deleted&quot;,
        }
    )

i am using odoo for backend,

i have add this code ini my php code

  &lt;?php
header(&#39;Access-Control-Allow-Origin: *&#39;);

?&gt;

but still CORS not allowed, how to fix this ?

答案1

得分: 4

读取错误消息时要仔细检查。不要只关注单词"CORS"并忽略错误消息的其余部分。

错误提示说问题在于预检请求的响应没有OK状态。它没有提到"Access-Control-Allow-Origin"标头。

如果你查阅一下预检请求,你会发现它是一个OPTIONS请求,请求允许执行你试图进行的GET请求。

它没有OK状态,所以使用浏览器开发工具的网络选项卡来查看其状态是很重要的。如果你的服务器端代码只处理GET请求,而没有针对OPTIONS请求的路由,我不会感到惊讶,如果状态要么是404 NOT FOUND,要么是405 METHOD NOT ALLOWED。

创建一个适合的路由来响应预检请求(即使用OPTIONS方法)。

考虑查找你正在使用的框架的库/配置,这些库/配置可以为你处理CORS。

英文:

Read the error message carefully. Don't pick out the word "CORS" and ignore the rest of the error message.

The error says the problem is that the response to the preflight doesn't have an OK status. It says nothing about an Access-Control-Allow-Origin header.

If you look up what a preflight request is you'll see that it is an OPTIONS request that is asking permission to make the GET request that you are trying to make.

It doesn't have an OK status so use the Network tab of your browser's developer tools to see what the status of it is. I wouldn't be surprised if it was either a 404 NOT FOUND or 405 METHOD NOT ALLOWED because your server-side code doesn't have a route for an OPTIONS request, only for a GET request.

Create a suitable route to respond to the preflight request (i.e. with the OPTIONS method) with.

Consider looking for a library / configuration for the framework that you are using which will take care of CORS for you.

huangapple
  • 本文由 发表于 2023年3月3日 17:53:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定