Skip to content
Advertisement

React Native call Odoo API via Axios struggling with CORS

I am using React Native, and trying to call Odoo APIs using Axios.

This is how I successfully call authenticate on my local Odoo instance.

const authenticate = await axios.post('http://localhost:8069/web/session/authenticate',
    {
        params: {
            db: 'db',
            login: 'odoo',
            password: 'odoo',
        }
    }
);

Now that I got the result from Odoo. I want to call methods and query some records.

So, I tried to get some records from DataSet search_read first.

Here is what I tried.

const search_read = await axios.post('http://localhost:8069/web/dataset/search_read',
    {
        params: {
            model: 'stock.picking',
            fields: ['id','name'],
        }
    }
);

It gave me this error.

Access to XMLHttpRequest at ‘http://localhost:8069/web/dataset/search_read’ from origin ‘http://localhost:19006’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Even though I already inherited and customized both @http.route to allow CORS in the Odoo side.

from odoo.addons.web.controllers.main import Session, DataSet
from odoo import http


class SessionInherit(Session):

    @http.route('/web/session/authenticate', type='json', auth="none", cors='*')
    def authenticate(self, db, login, password, base_location=None):
        return super(SessionInherit, self).authenticate(db, login, password, base_location)

    
class DataSetInherit(DataSet):

    @http.route('/web/dataset/search_read', type='json', auth="user", cors='*')
    def search_read(self, model, fields=False, offset=0, limit=False, domain=None, sort=None):
        return super(DataSetInherit, self).search_read(model, fields, offset, limit, domain, sort)

How do I solve this problem?

Note: The authentication request also had CORS problem before I customized the authenticate method to allow it. Once I did, it works fine. However, when I do the same for search_read, it still gives me CORS error.

Advertisement

Answer

Try xml-rpc or json-rpc.

Consuming XML-RPC in React Native

https://www.odoo.com/documentation/14.0/developer/api/external_api.html

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement