Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
XmlHttpRequest con encabezados personalizados: la respuesta para la verificación previa no pasa la verificación de control de acceso

Tengo un problema con una solicitud GET de ajax en el servidor REST. Hice algunas pruebas y las publicaré aquí.

En el servidor REST tengo dos métodos:

  • 1) resource_new_get (devuelve datos json y no necesita un encabezado personalizado)
  • 2) resource_api_new_get (resulta los mismos datos json que el primero, pero necesita un encabezado personalizado Api-Key)

Este es el código javascript que realiza la solicitud ajax en el servidor (en el método resource_new_get):

 app.updateResources = function(data) { if(data == null) { $.ajax( { url: 'http://<remotehost>/api/events/resource_new?id_event=<ID>', dataType: 'json', success: function(d) { console.log(d); }, error: function(error) { console.log('error ' + JSON.stringify(error)); } }); } else { ... } };

En este caso, la solicitud ajax funciona bien y puedo obtener la respuesta json del servidor.

Pero cuando realizo una solicitud a resource_api_new agregando encabezados personalizados de la siguiente manera:

 app.updateResources = function(data) { if(data == null) { $.ajax( { url: 'http://<remotehost>/api/events/resource_api_new?id_event=<ID>', dataType: 'json', headers: {'Api-Key': '<my_token>'}, success: function(d) { console.log(d); }, error: function(error) { console.log('error ' + JSON.stringify(error)); } }); } else { ... } };

Que necesita un token identificado por la clave 'Api-Key' en los encabezados para devolver la respuesta json, la función de error se activa y devuelve esto:

 XMLHttpRequest cannot load http://<remotehost>/v2/index.php/api/events/resource_api_new?id_event=<ID>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://<myhost>' is therefore not allowed access. The response had HTTP status code 404.

Cuando agrego en la parte superior del archivo php, que contiene REST Server, la siguiente línea:

header('Acceso-Control-Permitir-Origen: *');

La respuesta devuelve "simplemente" el código de estado HTTP 404, de la siguiente manera:

 XMLHttpRequest cannot load http://api.gtmasterclub.it/v2/index.php/api/eventi/relatori_api_new?id_evento=159. Response for preflight has invalid HTTP status code 404
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Encontré la solución al problema:

El encabezado Api-Key no se incluyó en Access-Control-Allow-Headers y agregué simplemente esto:

 Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Api-Key

Además, agregué un constructor para manejar la solicitud de OPCIONES, como se explica aquí:

Error de OPCIONES HTTP en Codeigniter Restserver y Backbone.js de Phil Sturgeon

 function __construct() { parent::__construct(); $method = $_SERVER['REQUEST_METHOD']; if($method == "OPTIONS") { log_message('debug', 'method OPTIONS called'); die(); } }

Y, en el script del cliente, eliminé:

 data-type: 'json',
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!