我无法从TODO应用中删除项目。 我正在使用react和axios进行删除。 这是我在“网络”标签中遇到的错误。
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 onClick={() => this.handleDelete(item)} className="btn btn-danger">
Delete
</button>
答案 0 :(得分:1)
一个更好的解决方案是代理React App的API调用。创建React App为您提供了解决方案。
首先,我想告诉您此方法仅适用于使用Create React App创建的应用程序,并且此代理仅在开发环境中作为开发功能起作用,不适用于生产版本。您只需向名为[l,r]
的{{1}}添加一个新密钥,然后重新启动服务器。
r
现在,您完整的package.json
文件看起来像这样。
proxy
对于"proxy": "http://localhost:8000/",
请求,您可以致电:
package.json
上面的代码与CORS无关。
从手册中...
请记住,
{ "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()); };
之类的URL指向正确的内容在生产中。您不必使用proxy
前缀。没有npm start
接受标头的所有无法识别的请求都将重定向到指定的/api/todos
。
因此,它确实是特定于开发目的,而不是用于生产级别。这有助于与将来进行类似的设置,并且避免了所有疯狂的本地主机hacky架构来适应环境。
我写了一篇博客文章,详细介绍了如何设置此内容-Using React's Proxy to get ahead of CORS & use HTTPS for API calls。希望这会有所帮助。
答案 1 :(得分:0)
<button>onClick={()=>this.handleDelete(item)}>delete</button>
为了防止自动提交按钮,请不要这么做,我们需要如上所述编写删除按钮