Using the fetch API to query an endpoint to get a json response and getting back an empty response error

Please forgive the long debug info and code. I figure its all relevant.

Im trying to query an api endpoint to get a ticket back. I query using postman and get the ticket response back as text that is shown in the headers tab. However, I want to use java script to get that ticket back and do other stuff with it. When i run the script, it logs an error to the console:

SyntaxError: Unexpected end of input
    at FetchDemo.html:48
(anonymous) @ FetchDemo.html:54

Promise.catch (async)
getTicket @ FetchDemo.html:53

the response i get is this:

type: "opaque"
url: ""
redirected: false
status: 0
ok: false
statusText: ""
headers: Headers {}
body: (...)
bodyUsed: false
__proto__: Response

My code is below:

<script>

let URL = 'https://jsonplaceholder.typicode.com/posts/';
let TabURL = 'http://15.222.0.10/trusted/?username=admin';

document.getElementById("getTicket").addEventListener('click',getTicket);



function getTicket() {
    console.log("in side getTicket");
    //setup an options array to pass into the fetch call
    let options = {
        method: 'POST',
        mode: 'no-cors',
        headers: {
            'Accept' : 'application-json,*/*',
            'Content-Type' : 'application:json'
        }
    };


    console.log(TabURL);
    console.log(options);
    fetch (TabURL,options)
        .then(response => {
            console.log(response);
            return response.json();
        })
        .then(response => {
            console.log(response);
        })
        .catch(error => {
            console.error(error);
        });

}

</script>

Upvotes: 0

Views: 196

Answers (1)

Evert
Evert

Reputation: 99523

From the specs:

An opaque filtered response is a filtered response whose type is "opaque", URL list is the empty list, status is 0, status message is the empty byte sequence, header list is empty, and body is null.

The reason you're getting an opaque response, is because you use the no-cors flag. If you want to do cross-domain requests such as these, you need CORS.

Upvotes: 1

Related Questions