-2

First, I try to send request by browser, everything is ok.

Second, I tried following code, the console of Microsoft Edge show this error:

Access to fetch at 'https://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=hello&callback=JSON_CALLBACK' from origin 'http://127.0.0.1:5500' 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.

<body>
    <h1>Hello</h1>
    <script>
        (async function (){
            let response = await fetch("https://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=hello&callback=JSON_CALLBACK", {
                method: "GET",
            })
            let text = await response.text();
            console.log(response);
            console.log(text);
        })();
    </script>
</body>

Then, I add mode property like this:

let response = await fetch("https://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=hello&callback=JSON_CALLBACK", {
    method: "GET",
    mode: "no-cors"
})

the console doesn't show error, but the response.ok is false, and the response.body is null.

enter image description here

but if i open network tool, I can see all data I want. enter image description here


I know if I want to get data by json padding, I should create a script label, and use docuemnt.body.appendChild(script) to get data. I just don't know why i failed by Fetch API.

Li Wenchi
  • 41
  • 3
  • 1
    *"I know if I want to get data by json padding, I should create a script label"* (you mean "tag" or "element"). Right. You can't do JSON with padding (which is really just loading a JavaScript script) with `fetch` or `XMLHttpRequest`, because those aren't mechanisms for running scripts. JSON with padding ("JSONP") is just a fancy name for a script that returns a function call passing in data. – T.J. Crowder May 06 '22 at 08:07
  • There are **dozens** of answered questions on this topic (whether it's CORS or JSONP). Please **[search](/search?q=%5Bjs%5D+Access+has+been+blocked+by+CORS+policy) [thoroughly**](/search?q=%5Bjs%5D+how+do+i+use+jsonp) before posting. More about searching [here](/help/searching). – T.J. Crowder May 06 '22 at 08:09
  • OK, english is not my first language, so I sometimes can't organize professional words to search for my problems clearly. – Li Wenchi May 16 '22 at 06:38

0 Answers0