2

I have this code:

async function my_function() {
    console.log("Hello");

    let response = await fetch(url, {
        mode: 'no-cors'
    })
        .then(response => response.json()) // THIS LINE

        .then(response => {
            console.log(response);
        })
}

which works great if I include const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args)); in node.js. This however, does not run in the browser. When I run this code in google chrome I get this error

Uncaught (in promise) SyntaxError: Unexpected end of input

relating to the

.then(response => response.json()) // THIS LINE

line. What am I doing wrong?

  • "*Unexpected end of input*" sounds like a JSON parse error to me. Can you verify in the devtools network panel that you're actually getting the response you were expecting? – Bergi Jan 31 '22 at 13:23
  • @Bergi — The JSON parse error is because the response is opaque because it is set to `no-cors` mode. – Quentin Jan 31 '22 at 13:33
  • @digitalniweb CORS is a fantastic technology as it allows you to lower the built-in security features of the browser when you want to share data and leave them up when it would be a risk to the user's data. – Quentin Jan 31 '22 at 13:37

2 Answers2

-1

For the browser, you have to enable the cors-policy otherwise it will not works. So in your API, you must include:

"Access-Control-Allow-Origin" : "*", 

And also disable the no-cors mode.

Konflex
  • 465
  • 3
  • 11
  • 1
    How do I do that, and if I later deploy this app, won't my users also have to do that? – JessicaJohnes Jan 31 '22 at 13:18
  • 1
    This isn't sufficient since you also have to disable no-cors mode. `"Access-Control-Allow-Credentials" : true` is pointless because the credentials mode is same-origin (the default). – Quentin Jan 31 '22 at 13:35
  • Yes i've updated my response, sorry for the confusion – Konflex Jan 31 '22 at 13:38
-1

Because You mixing Promises with await? Choice one of. Read about this https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

zbyso
  • 108
  • 5