Search code examples
javascriptpythonajaxcorsodoo-10

How do I do POST/GET request from AJAX to Odoo 10 custom module controller? (Blocked by CORS policy)


I am using Odoo 10 with a custom module and I created this simple controller. It works fine when i visit http://127.0.0.1:8069/cmodule/cmodule from the browser. It shows the return string.

I tried both GET and POST, but I get the same error result. Something about CORS policy blocking the request or something. My google powers haven't really found any way to resolve or any alternatives for this.

But when I try to request via AJAX from my other thing written in PHP/javascript. I get this error on javascript:

Access to XMLHttpRequest at 'http://127.0.0.1:8069/cmodule/cmodule/' from origin 'http://127.0.0.1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And this error from odoo:

2020-04-30 08:18:13,401 23156 INFO ? werkzeug: 127.0.0.1 - - [30/Apr/2020 08:18:13] "GET /cmodule/cmodule/ HTTP/1.1" 404 -

Here is the simple code from my Odoo-10 custom module controller:

# -*- coding: utf-8 -*-
from odoo import http

class Cmodule(http.Controller):
    @http.route('/cmodule/cmodule/', auth='public', cors='*')
    # I also tried here auth='none' and method='POST' and method='GET'
    def index(self, **kw):
        datas = http.request.env['product.product'].sudo().search(
            [('product_group', '=', 'assort')], limit=50)
        dstr = ','.join(datas )
        # {'ret_val': dstr }
        # I return {'ret_val': dstr } when doing POST request from AJAX.
        return dstr 

And here is the code from my AJAX request:

            $.ajax({
                type: "GET",
                // type: "POST",
                url: "http://127.0.0.1:8069/cmodule/cmodule/",
                // data: { data: 'HELLO' },
                success: function(response){
                    console.log(response);
                }
            });

Solution

  • While you are trying different things try simple authentication

    import odoo.addons.web.controllers.main as main
    class Home(main.Home):
        @http.route('/web/session/authenticate', type='json', auth="none" ,cors='*')
        def authenticate(self, db, login, password, base_location=None): 
        request.session.authenticate(db, login, password)
            return request.env['ir.http'].session_info()
    


    I had the same error when accessing it from IOS but worked fine with postman this, this code worked fine, well you did every thing in this code but still