-3

I am trying to update a line of text in my website with a value from a simple JSON file on another website. This is a slightly different question than the ones I've seen posted on stack - the reason being that I can't use JQuery (this is a school project), and I'm not supposed to use any back-end things, like Node/PHP/Angular/etc. I was wondering if it could be done with vanilla javascript?

I've tried a few different methods and the following gets me what I want, but I've had to use a chrome extension (Allow CORS) to work around the CORS error:

    let url1 = "https://www.codewars.com/api/v1/users/jrd656"

    let h = new Headers();
h.append('Accept', 'application/json');

let req = new Request(url1, {
    method: 'GET',
    headers: h,
    mode: 'cors',

});

fetch(req)
    .then((response)=>{
        if(response.ok){
            return response.json();
        }else{
            throw new Error('BAD HTTP stuff');
        }
    })
    .then( (jsonData) =>{
        console.log(jsonData);
    })
    .catch( (err) =>{
        console.log('ERROR:', err.message);
    });

The chrome extension only solves the issue for my browser and I want this to work for all browsers. I understand I could use a proxy, but this would require me to learn some back-end php/Node/etc, and I'd like to avoid that if possible.

I believe there is a way to overcome the CORS issue with: Access-Control-Allow-Origin: *;, but when I paste this in my .js file it doesn't work, and my browser gives me an error Uncaught SyntaxError: Unexpected token ':'.

JimmyTheCode
  • 3,783
  • 7
  • 29
  • 71
  • 2
    If you could easily circumvent CORS just by adding some lines to your request, why would it exist in the first place? It would be like locking your door and leaving the key inside lock. –  Dec 31 '19 at 11:14
  • Search for _"CORS"_ or _"Access-Control-Allow-Origin"_ here on SO. There are literally thousands of questions with this topic. Or just have a look at the _"Related"_ section: [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Andreas Dec 31 '19 at 11:14
  • The `Access-Control-Allow-Origin` header is not code and has to be set by the *target system* in their responses. You cannot give yourself access. –  Dec 31 '19 at 14:37
  • @ChrisG - It seems there are dozens if not hundreds of posts on the same topic so it must be a legitimate issue for a lot of people. – JimmyTheCode Dec 31 '19 at 14:41
  • 1
    @Andreas Thanks. That was eventually the solution I used. I had encountered it on my search previously, but it involved setting up other apps and I was holding out for a simpler solution. (I'm entry-level and these solutions tend to get me into more trouble than I can manage!). Hope you have a great day. – JimmyTheCode Dec 31 '19 at 14:44
  • @AlonEitan Thanks! I've been told not to use JQuery so I saw that post and decided to look further for a vanilla JS solution. I've sussed it now, but thanks for the help! – JimmyTheCode Dec 31 '19 at 14:45
  • @Amy Thanks! I'm sure you're right, but I seem to have worked it out now. Have a nice day! – JimmyTheCode Dec 31 '19 at 14:46
  • It's a legitimate issue alright, but if there are already X posts about this topic, then X-1 of them are duplicates and supposed to be closed, and all you've done is added another duplicate. stackoverflow isn't a "here's my problem, please solve it for me" kind of website, it's primarily about building a repository of solved questions. –  Dec 31 '19 at 14:52
  • @ChrisG Having spent several days researching, I'm yet to find a solution to my problem within my parameters. There are lots of solutions out there that use JQuery, PHP, etc. I don't want to delve into these languages/solutions. I've seen from comments all over the place that lots of people are in the same situation as me and would like a quick-fix solution in order to help them progress and develop a basic website. If I'd read this post three days ago, it would have saved me three days searching. If that's not part of the purpose of this site let me know (genuinely). – JimmyTheCode Dec 31 '19 at 15:20
  • Like I alluded to in my first comment, most APIs are supposed to be used from a backend and thus don't allow requests from other domains (i.e. JS/jQuery in-browser code). The fact that lots of people don't want to have to acquire the required skills first doesn't mean it'll work without them somehow. I'm not sure what your point is. If you can't find a solution within your parameters, maybe you need to adjust your parameters? –  Dec 31 '19 at 15:27
  • @ChrisG makes sense. I didn't know any of this and am still learning. I had to figure out that there was no solution within my parameters before I knew that I needed to adjust my parameters (hence my question). I guess that's where I'm at now. Apparently I've unwittingly done this wrong. Should I delete my post do you think? – JimmyTheCode Dec 31 '19 at 15:33

1 Answers1

-1

I couldn't find an solution to my specific problem (I don't think it exists). I ended up solving the problem by following the directions on here: No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

It involved spending 10 minutes cloning a heroku app that acted as a proxy to handle the data I needed.

Hopefully anyone with the same issue can read this and it will save them time. I've spend (literally) days trying to figure this out, so if you've arrived here, I'd just do the above link and save yourself any more trial and error.

JimmyTheCode
  • 3,783
  • 7
  • 29
  • 71
  • 1
    I'm really sorry but this is simply not how SO works. An answer is supposed to be a full answer, it's not supposed to send the reader elsewhere. If the answer already exists on SO, the question is a dupe and will be removed. If the answer exists elsewhere, you're supposed to post the relevant parts in the answer, because links to other websites will rot. –  Dec 31 '19 at 14:57
  • 1
    This is a bad solution anyway and shouldn't be recommended except for short-term hobbyist or school projects. The owners of the target systems don't want you using their resources and have locked the door, and the chosen solution is just to climb through the window. –  Dec 31 '19 at 15:08
  • @ChrisG Thanks Chris. I don't believe this question is a duplicate, as I've still not seen any other solution elsewhere. The solution I've linked to is more complicated than I was looking for (I wanted to limit to just using vanilla js, css, and html - since that's the requirements of the challenge I'm trying to do). But it's the closest I've found. I thought it would be worth putting up as a solution in case anyone got stuck in the same place as me. – JimmyTheCode Dec 31 '19 at 15:27
  • You cannot circumvent CORS with pure client-side JS, period. Again, if it were that easy, *why would CORS exist in the first place*? –  Dec 31 '19 at 15:29
  • @Amy This is a school project. Thanks for pointing that out, I've editted my question to reflect that. – JimmyTheCode Dec 31 '19 at 15:29
  • 1
    @ChrisG I'm sure there is good reason for CORS to exist, but I think it's also true that lots of websites provide publicly available API's that I don't need to be blocked by CORS. All I wanted to do was update my webpage from publicly available information from another website. For whatever reason CORS was needlessly (from my understanding) obstructing this. – JimmyTheCode Dec 31 '19 at 15:36
  • 1
    Needlessly, as in the same reason you lock the door to your house? You are using a resource that does not belong to you. It isn't up to you whether they permit you access or not. That's *their* decision. CORS was created to prevent websites from ripping off of the work of others. Without it, you could create your own "search engine" that does nothing but presents google's results to the user, but with your branding. They built it, they should receive some compensation. CORS prevents people from ripping them off. Needlessly, indeed. –  Dec 31 '19 at 15:40
  • 1
    @Amy I understand that, but there wasn't any need for it to be obstructing info in my case. This is the case for thousands of other people, so I don't think this an irrelevant topic. – JimmyTheCode Dec 31 '19 at 16:32
  • @JamesDaniels Yes, of course, it's different for you. I see now. –  Dec 31 '19 at 17:13