0

I am new to vueJS and version using is 2.0. I need to fetch some JSON data from url. Using javacsript fetch methods to get the data from URL. below is my code,

function getValue() {
            const requestOptions = {
                method: "GET",
                header: {"Access-Control-Allow-Origin": "GET"}
            };
              fetch("http://api.plos.org/search?q=title:DNA", requestOptions)
                .then(
                    (response) => {
                        console.log(response.json());
                    }
                );
        }

        getValue();

I am getting CORS issue like,

Access to fetch at 'http://api.plos.org/search?q=title:DNA' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I tried all the possibilities which available in stack-overflow. But no luck. Any help would be much appreciated. JSFiddle link - https://jsfiddle.net/m45hsekf/

Deepak
  • 119
  • 1
  • 8

3 Answers3

0

CORS should be enabled at server level like node or java application.

Access-Control-Allow-Origin : "test-client.com" or use "*"(not recommended). Then allow this value at the server

Get is your http method not the origin value

To enable in node use this line

res. header("Access-Control-Allow-Origin", "*"); // again * is not a best practice. Please accept this as answer too

Refer to the url below for more info https://dzone.com/articles/cors-in-node

Atul Chaudhary
  • 3,698
  • 1
  • 31
  • 51
0

Did you tried to set the mode to no-cors like the error suggests to you?

set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tested it and it works:

const requestOptions = {
      method: "GET",
      mode: "no-cors"
};

So the request looks like this:

fetch("http://api.plos.org/search?q=title:DNA", {
  mode: "no-cors"
})
  .then(response => response.json())
  .then(result => {
    console.log(result);
  });
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Tried this, and getting error like `Uncaught (in promise) SyntaxError: Unexpected end of input` in `response.json()`. Dont know whats the reason – Deepak Jun 18 '20 at 06:29
  • then check this out https://stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input – bill.gates Jun 18 '20 at 06:33
0

when i have problems while i develop, i use crhome extension called CORS UNBLOCK, then i can test my api, and when i deploy to final server, always is in the same domain then i havent cors ploblem