0

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>
  • In the above, what lines correspond to lines 48 and 54 in your original code? – T.J. Crowder Dec 30 '19 at 17:48
  • The `status: 0` and `ok: false` tell us that the fetch failed. If you're doing this in a browser (as you appear to be), that's probably because of the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) preventing access. Look for an error talking about a cross-origin being blocked. See: [*Why does my JavaScript code get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?*](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-get-a-no-access-control-allow-origin-header-is-pr) – T.J. Crowder Dec 30 '19 at 17:50
  • Duplicate of: https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors – T.J. Crowder Dec 30 '19 at 17:55

1 Answers1

1

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • Of course, if they remove the `no-cors`, they'll probably get an error because of the SOP... – T.J. Crowder Dec 30 '19 at 17:52
  • @T.J.Crowder: correct. Cross-domain requests require actual CORS headers. You can't really cheat – Evert Dec 30 '19 at 17:53
  • Frankly, this just seems like a duplicate of https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-get-a-no-access-control-allow-origin-header-is-pr to me (sadly, I marked it "unclear" first, so...). But perhaps the `no-cors` part is new. – T.J. Crowder Dec 30 '19 at 17:54
  • Nope, it's a duplicate of https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors. – T.J. Crowder Dec 30 '19 at 17:55
  • Ok, i understand the issue with cors. However, if I don't have access to the server code (ie, its a seperate piece vendor software), how do i fix the issue? I thought putting the no-cors in the header was a solution, however I don't even get my response back without it. Can you guys help? (also, sorry about the duplicate. I searched briefly and didn't find that one) – Chris Gauthier Winnipeg Dec 30 '19 at 20:15
  • @ChrisGauthierWinnipeg the idea of CORS is to explicitly allow other domains to access your server. If you don't have the ability to change server headers, you cannot make this request. If you did, there would be a major security problem. Your only real option is to use a different server to access the original API on your behalf. As a sort of proxy. – Evert Dec 31 '19 at 16:23
  • By the way, just so this doesn't get un-answered. The solution i wrote to complete this task was to take the rest call out of the browser-viewable java script file. I built an application in spring boot that used the rest-template api to take the browser out of the picture completely. I am now using angular to call the rest point on the boot application. I still have issues because spring boot seems to be generating a text response and angular seems to want java script, but Im working through that now. Thanks for your help, gents. – Chris Gauthier Winnipeg Jan 23 '20 at 20:24
  • @ChrisGauthierWinnipeg, this makes sense and exactly what i more or less suggested. Best way to call the API is to do it server-side yourself, where you have 0 restrictions – Evert Jan 23 '20 at 22:03
  • Can you possibly give me a resource on doing that? That will save me some search time (which i don't mind, but not sure i understand the technique enough to do so) – Chris Gauthier Winnipeg Jan 23 '20 at 22:29
  • I don't really have a resource, but to sum it up: You need your own backend (like Spring) and in this backend you make the rest call. Then your frontend can call your backend to get the data. It sounds like you're mostly doing that already though – Evert Jan 23 '20 at 22:37
  • oh..yeah, thats exactly what im doing. My problem is that i have my spring-boot application dishing out a json response, but my angluar service (using the HttpClient http.get method) isn't displaying the json response in the component.html file – Chris Gauthier Winnipeg Jan 23 '20 at 22:48
  • I can give you more info, if you think you can help – Chris Gauthier Winnipeg Jan 23 '20 at 22:49
  • I use none of those technologies, so you can't help you there! – Evert Jan 24 '20 at 02:20