2017-02-16 2 views
1

ich auf localhost möchte folgende in Javascript tun:kehrt 400 holen beim Verfassen eines Beitrags

curl --data "client_id=admin-cli&username=xx&password=xx&grant_type=password" http://localhost:8082/auth/realms/mine/protocol/openid-connect/token 

Und hier ist mein Versuch:

const data = {"client_id":"admin-cli","username":"xx","password":"xx,"grant_type":"password"}; 
    const formData = new FormData(); 
    for(name in data) { 
     formData.append(name, data[name]); 
    } 
    fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token", { 
     method: "POST", 
     body: formData 
    }) 
     .then(function (response) { 
      return response.text(); 
     }) 
     .then(function (text) { 
      console.log('Request successful', text.length,text); 
     }) 
     .catch(function (error) { 
      console.log('Request failed', error) 
     }); 

, die den Fehler produziert:

POST http://localhost:8082/auth/realms/mine/protocol/openid-connect/token 400 (Bad Request) 
localhost/:1 Fetch API cannot load http://localhost:8082/auth/realms/mine/protocol/openid-connect/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:18080' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 
bundle.js:24428 Request failed TypeError: Failed to fetch 

Was mache ich falsch? Ich mache einen Proof of Concept, damit ich mit jeder Lösung zufrieden bin, solange sie mir das Token zurückgibt.

habe ich auch versucht:

fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token?client_id=admin-cli&username=sa&password=sa&grant_type=password", { 
      method: "POST" 
     }) 

mit dem gleichen Ergebnis.

Antwort

1

Die -d/--data Option für curl sendet Anfragen mit Content-Type: application/x-www-form-urlencoded und mit den Daten wie eine Abfrage-String, als einzelne Zeichenfolge mit den Parametern getrennt durch & und die von = voran Werte formatiert.

Damit nacheifern, dann würden Sie tun müssen:

fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token", { 
    method: "POST", 
    headers: { 
     "Content-type": 
     "application/x-www-form-urlencoded; charset=UTF-8" 
    }, 
    body: 
     "client_id=admin-cli&username=xx&password=xx&grant_type=password" 
}) 

FormData formatiert seine Daten als multipart/form-data, das nicht das, was Sie wollen, wenn Ihr Ziel ist, dass curl Anruf zu replizieren ist.

1

Körperattribut verwendet JSON-String. Sie können bitte Folgendes versuchen Beachten Sie auch, dass HTTP-Anfragen Get und Head keine Körpern haben können.

fetch("http://localhost:8082/auth/realms/mine/protocol/openid-connect/token", { 
    method: "POST", 
    body: JSON.stringify(formData) 
}) 
Verwandte Themen