Header api fetch

bonjour,

je souhaite consommer api REST avec fetch mais ça marche pas quand je passe les paramètres dans la requête.

exemple

fetch('https://monsite.fr/api/index.php/users/info', {
  method: "GET",
  headers: {'DOLAPIKEY': "aaaaaaaaaaaaaaaaaaaaaaaaa"} 
})
.then(response => response.json()) 
.then(json => console.log(json)); 

ne marche pas, j’ai une erreur sur

  • la method GET avec NS_ERROR_DOM_BAD_URI le transfert

  • la methode OPTIONS avec CROS Failed sur le transfert

par contre ça marche sans souci quand je passe le token dans url

fetch('https://monsite.fr/api/index.php/users/info?DOLAPIKEY=aaaaaaaaaaaaaaaaaaaaaaaaa')
.then(response => response.json()) 
.then(json => console.log(json)); 

savez vous d’ou viens le probleme ?
Merci d’avance

PS j’ai testé avec CURL ca marche

Le problème pour CORS c est que vous faites un appel cross-domaine, donc il faut que dolibarr envoie un header pour dire qu’il accepte cet appel

voici le code à mettre dans htdocs/api/index.php

if (isset($_SERVER['HTTP_ORIGIN'])) {
    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
    // you want to allow, and if so:
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// Access-Control headers are received during OPTIONS requests
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, HEAD, DELETE");
    }

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    }
    header('Content-Length: 0');
    exit();
}

ce code est un peu bourrin, car il laisse tous les domaines, mais pour tester ce sera bien

1 « J'aime »

salut dev2z
merci ca marche