Reactjs 我正在尝试使用axios和django从TODO应用程序中删除项目

Reactjs 我正在尝试使用axios和django从TODO应用程序中删除项目,reactjs,api,axios,Reactjs,Api,Axios,我无法从TODO应用程序中删除项目。 我正在使用react和axios进行删除。 这是我在“网络”选项卡中遇到的错误 Provisional headers are shown Origin: null Referer: http://localhost:3000/ handleDelete=项目=>{ axios .删除(`http://localhost:8000/api/todos/${item.id}`,item) .then(res=>this.refreshList()); };

我无法从TODO应用程序中删除项目。 我正在使用react和axios进行删除。 这是我在“网络”选项卡中遇到的错误

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

<button onClick={() => this.handleDelete(item)} className="btn btn-danger">
  Delete
</button>
this.handleDelete(项目)}className=“btn btn danger”>
删除

这是“网络”选项卡的屏幕截图。

更好的解决方案是代理React应用程序的API调用。CreateReact应用程序为您提供了一个解决方案

Provisional headers are shown
Origin: null
Referer: http://localhost:3000/
在此之前,我想告诉您,此方法仅适用于使用Create React App创建的应用程序,而且此代理仅作为开发功能在开发环境中工作,不适用于生产构建。您只需向名为
proxy
package.json
添加一个新密钥,然后重新启动服务器

"proxy": "http://localhost:8000/",
现在,您完整的
package.json
文件如下所示

{
  "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"
  }
}
对于
DELETE
请求,您只需拨打:

handleDelete = item => {
  axios
    .delete(`/api/todos/${item.id}`, item)
    .then(res => this.refreshList());
};
上述代码与CORS无关

从手册上

请记住,
proxy
仅在开发中有效(使用
npm start
),您需要确保像
/api/todos
这样的URL在生产中指向正确的东西。您不必使用
/api
前缀。没有
text/html
accept头的任何无法识别的请求将被重定向到指定的
代理

因此,它确实是专门用于开发目的,而不是用于生产级别。这有助于未来的工作,在未来有类似的设置,并避免所有疯狂的本地主机黑客架构,以适应环境

我写了一篇博客,详细介绍了如何设置这个东西。希望这有帮助。

onClick={()=>this.handleDelete(item)}>delete
<button>onClick={()=>this.handleDelete(item)}>delete</button>

为了防止自动提交按钮,我们需要像上面提到的那样编写删除按钮

,这在我看来并不是一个错误。你能看到是什么引发了这个错误吗?它会在控制台中找到启动器的位置。另外,你能检查一下网络选项卡,看看它是怎么说的,比如HTTP状态码、删除主体等等。还是只是飞行前的故障?请看看这个问题,可能也是你的情况:@gazdagergo这个问题很久以前就解决了。无论如何,Chrome不允许CORS localhost,你可以通过安装这个扩展来处理它:@Amnahkhatun然后你就可以通过这种方式访问了:
.delete(`/api/todos/${item.id}`,item)
-这将完全解决这个问题。是的,我用同样的方式写的。这是我在响应选项卡中得到的:``{“详细信息”:“CSRF失败:CSRF令牌丢失或不正确。”}``@Amnahkhatun您可以使用imgur发送网络选项卡内容的屏幕截图吗?我无法添加images@Amnahkhatun上面写着禁止。真奇怪。