1

I am unable to delete items from TODO app. I am using react and axios for deleting. Here is the error I am getting in network tab.

Provisional headers are shown
Origin: null
Referer: http://localhost:3000/
handleDelete = item => {
  axios
    .delete(`http://localhost:8000/api/todos/${item.id}`, item)
    .then(res => this.refreshList());
};

Button:

<button onClick={() => this.handleDelete(item)} className="btn btn-danger">
  Delete
</button>

Here is the screenshot of network tab.network tab

The IT gal
  • 197
  • 1
  • 5
  • 15

2 Answers2

1

A better solution for this is to proxy the API Calls for your React App. Create React App provides you with a solution.

Before anything, I would like to tell that this method applies only for the applications that are created using Create React App and also this proxying works only on the development environment as a development feature and is not available for the production build. You just need to add a new key to the package.json called proxy and then restart the server.

"proxy": "http://localhost:8000/",

Now, your complete package.json file looks something like this.

{
  "name": "project-name",
  "version": "1.0.0",
  "private": true,
  "proxy": "http://localhost:8000/",
  "dependencies": {
    "react": "^16.8.4",
    "react-scripts": "2.1.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}

And for the DELETE requests, you can just call:

handleDelete = item => {
  axios
    .delete(`/api/todos/${item.id}`, item)
    .then(res => this.refreshList());
};

The above code will have nothing related to CORS.

From the manual...

Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production. You don’t have to use the /api prefix. Any unrecognized request without a text/html accept header will be redirected to the specified proxy.

So it is indeed specific for development purposes and not for a production level use. This helps in working with the future, where there's this similar setup and avoids all the crazy localhost hacky architecture for gearing with the environment.

I wrote a blogpost detailing how to set this thing up - Using React's Proxy to get ahead of CORS & use HTTPS for API calls. Hope this helps.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0
<button>onClick={()=>this.handleDelete(item)}>delete</button>

Please not that inorder to prevent automatic button submission, we need to write delete button as mention above

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Anoop K George
  • 1,605
  • 12
  • 40