iamaprogrammer
iamaprogrammer

Reputation: 135

Why am I getting three "Cross-Origin Request Blocked" messages

I have a Svelte application and I am trying to render data from the API but I keep on getting three error messages.

The code works properly on node but not on Svelte.

Below is the Svelte code:

<script lang="ts">
  import { onMount } from "svelte";

  let word = [];
  onMount(async () => {
    const response = await fetch(
      "https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5",
      {
        method: "GET",
        headers: {
          "X-RapidAPI-Key": "KEY",
          "X-RapidAPI-Host": "random-words5.p.rapidapi.com",
        },
      }
    );
    word = await response.json();
    console.log(word);
  });
</script>

<p>{word}</p>

And below are the error messages:

ross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:5173’).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS request did not succeed). Status code: (null).

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

How do I get my code to render out the data from the API in Svelte?

Upvotes: 0

Views: 1113

Answers (1)

Ryuman
Ryuman

Reputation: 1057

The CORS issue occurs when you try to fetch a resource from a local environment, this is the case when you run your app in dev mode.

I use the CORS Unblock extension to fix the issue, give it a try.

Upvotes: 2

Related Questions