0

I am learning how to use fetch api in javascript. I tried running the following script in my localhost. However, there was nothing logged to the console. Also there was no error displayed regarding this. Many posts say that CORS might be the issue here. Can you please give an example to resolve this? Please advise.

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(json => console.log(json));

Please comment if you require more information.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
MVG
  • 314
  • 1
  • 3
  • 17
  • Your code seems to work when wrapped in function: https://codepen.io/tomekbuszewski/pen/qBOqMxQ?editors=0010 Please post more of your code, maybe there's something else blocking it. – Tomek Buszewski Apr 22 '20 at 06:18
  • I ran you code in codepen and it displayed the output in the console. Are you using this with vanilla javascript or with a framework? – Christopher Dias Apr 22 '20 at 06:19
  • Your code works. I made a snippet. You CANNOT run it from a file system. So when you say localhost you need to call it from `http://localhost....` and possibly you will get console errors that it is not running on https – mplungjan Apr 22 '20 at 06:25

1 Answers1

0

You need to receive the following headers:

  • Access-Control-Allow-Origin: * (or whatever host you want to restrict to)
  • Access-Control-Allow-Methods: * (or whatever methods you want to restrict to)
  • Access-Control-Allow-Methods: Content-Type

Note the last one which is also important because you are setting Content-Type: application/json;charset=UTF-8. If you have any other custom headers you will need to add those too.

These are all to be done on the server though, your app doesn't need to do anything else.

Alternatively (if possible) you can opt to not use application/json at all and set your Content-Type to application/x-www-form-urlencoded, multipart/form-data, or text/plain and no preflight (OPTIONS) request will be done and it won't matter if CORS is enabled on the server or not.

Kiran Mistry
  • 2,614
  • 3
  • 12
  • 28