1

I can't figure this out!

(I've modified id codes for privacy...)

This works:

curl -vvv -H "Authorization: Bearer 3t8D7CeQ3MDPADCI" -X "DELETE" https://www.blockonomics.co/api/button?uid=8778e542911eb-ff979c

But in my Reactjs module, this does not work:

// urlDelete = 'https://www.blockonomics.co/api/button?uid='
// item = '8778e542911eb-ff979c'

const handleDelete = async (item) => {   
    const url = urlDelete + item

    await axios
      .delete(url, {
        headers: {
          Authorization: 'Bearer 3t8D7CeQ3MDPADCI',
        },
      })
      .then((res) => {
        console.log(res.status)
      })
  }

Errors:

I've tried adding a cors-anywhere proxy to the url with no success. I've tried using 'GET' and 'POST', still nothing.

Why does the curl command work but the axios function doesn't?

I'd really appreciate some advice about this. I'm stuck!

Sandy
  • 23
  • 6

1 Answers1

1

CORS is specific to the browser, and cURL operates outside of the browser. There are security reasons browsers don't let JS served from one place (like localhost) access resources on another domain unless the response says, in effect, "Yes, I'm fine with localhost or sandys-server.com making this call" or "I'm fine with anyone, anywhere, making this call". Since blockonomics.co isn't returning any CORS info that I can see, your browser won't let you make this call. You can disable CORS in your browser (see this answer) but you should not. Plus, if your app is supposed to be used by other people, it's going to be hard to get them to disable CORS before they can use it, so it's a self-defeating way to un-block yourself.

You have a couple options to move forward if you can't control the headers returned by blockonomics.co:

  1. Proxy your API request. You can run something (nginx, a little Flask app) locally that will pass your request to blockonomics, and add a permissive CORS header to the response. If you want your app to work outside of your local dev environment, you'll also need to have that proxy in place on the internet. Keep in mind other people will be able to use it, so you probably wouldn't want to use the wildcard in your response!

  2. Mock the response locally, maybe as part of your tests, if you won't have this problem in production.

Jim J
  • 546
  • 3
  • 11
  • 1
    I appreciate that you took the time to answer me, Jim. CORS is still a very confusing concept for me, but you have shed some light on the subject. Thank you. I ended up using a Cloudfare worker. I had written one in a panic that had a tiny error in it. I also assumed that my computer was haunted, which is actually why I think it didn't work the first time... but... the problem has finally been solved. Tiny error caught. Panic subsides. I think that your explanation will help a lot of other people who are struggling with the same problem. Thanks again for your time and your clear explanation :) – Sandy Feb 07 '21 at 21:13