-1

I am trying to send a fetch request to AWS API gateway but it keeps giving me this error. I am doing it from the admin side in WordPress.

Access to fetch at 'https://34557322456.execute-api.ap-southeast-1.amazonaws.com/V1/code?kdata=something' from origin 'https://mywebsite.online' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

This is the request

fetch('https://34557322456.execute-api.ap-southeast-1.amazonaws.com/V1/code?kdata=something', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        },
      }).then(response => {
        return response.json()
      })
      .then(data => console.log(data))
      .catch(error => console.log(error));

Please help

1 Answers1

0

The headers should be on the server side, try something like this in your .php file:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: 'X-Requested-With,content-type'");
header("Access-Control-Allow-Methods: 'GET, POST, OPTIONS, PUT, PATCH, DELETE'");
  • Tried this but with no success. Did you mean that api server is blocking me or my website is blocking me? –  Jan 09 '21 at 06:41
  • The browser blocks you because the response lacks the Access-Control-Allow-Origin response header. Try to remove the headers from the options on fetch, your request had 'Content-Type: application/json', and triggered a CORS preflight. – DenisDaniel707 Jan 09 '21 at 06:51
  • I have a landa function with python which generates the response from the server side. Do you mean the response generated by the api is missing the Access-Control-Allow-Origin? Sorry If I sound dump –  Jan 09 '21 at 06:55
  • Well then try something like this, I did not try in python but I guess this is how you set the headers there, the response from the server should contain the headers: https://stackoverflow.com/a/50067910/14755337 if this fails then there is a CORS plugin for Chrome like: https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc that should enable and disable CORS with a click – DenisDaniel707 Jan 09 '21 at 06:58
  • hah I enabled that header in the response, it fails :( –  Jan 09 '21 at 07:10