AnsweredAssumed Answered

AJAX to Sugar REST blocked by CORS

Question asked by Artis Plocins on Jun 21, 2017
Latest reply on Aug 8, 2018 by Denise Ingram

I tried sending an AJAX request with jQuery to a SugarCRM REST endpoint, but it was blocked by Cross Origin Resource Sharing and returned HTTP 404 along with an error.

 

This is the AJAX request:

 

$.ajax({
        type: 'POST',
        url: 'https://example.sugarinstance.com/rest/v10/Cases/web/submit',
        data: jsonData,
        dataType: 'json',
        contentType: 'application/json',
        success: function(response) {
          console.log('SUCCESS')
          console.log(response)
        }
      })

And this is the error returned:

XMLHttpRequest cannot load https://example.sugarinstance.com/rest/v10/Cases/web/submit. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

This is the endpoint I created just to test without authentication since it was not working at all:

<?php

class Web2CaseApi extends SugarApi
{
    public function registerApiRest()
    {
        return array(
            'Web2CaseEndpoint' => array(
                'reqType' => 'POST',
                'noLoginRequired' => true,
                'path' => array('Cases', 'web', 'submit'),
                'method' => 'newCase',
                'shortHelp' => 'Receives JSON data for a new Case record',
            ),
        );
    }
    public function newCase($api, $args)
    {
        return $args;
    }
}

This endpoint now appears in the API help, so it definitely exists.

 

How am I supposed to use AJAX to send data to SugarCRM if it is blocked?
Should the server be set to allow CORS by default?

I also tried these options in the jQuery AJAX request to no avail:

crossDomain: true,
headers: {
  'Access-Control-Allow-Origin': '*'
},

Outcomes