在我的组件中,它以 componentDidMount() 生命周期开始,获取数据显示在一个表格上。
componentDidMount() {
fetch(TABLE_DATA, {
//TABLE_DATA is a global variable that runs a callback which combines the rest of the variable
//to the url. It's mostly for deployment; an easy way to change urls back and forth.
credentials: 'include',
methods: 'GET',
headers: {
'Content-type': 'application/json',
},
})
.then(res => res.json())
.then(data=>{
this.setState({
tableData: data,
isLoaded: true
})
})
}
现在,当我想在同一个组件中的表单上提交一些信息时,由于某些原因,TABLE_DATA变量覆盖了我所获取的任何URL。下面是提交表单的代码。
submitAccountToUser= e => {
e.preventDefault()
fetch(EXTRA_INFO, {
credentials: 'include',
methods: 'POST',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
'info':this.state.info
})
})
.then(res => console.log('res', res))
//doesn't get to this console.log. It stops on the line with "fetch(EXTRA_INFO
}
EXTRA_INFO被覆盖为TABLE_DATA. 在我的本地服务器终端上显示有一个 "GET "方法在TABLE_DATA url处被调用。在我的浏览器中也出现了这个错误。
Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': 使用GETHEAD方法的请求不能有body。
这就说得通了,因为最初的fetch调用(TABLE_DATA)只是一个'GET'请求,不能有body。但它应该连这个url都不会取。我已经通过查找语法错误和检查全局变量中的url来保持简单。但我不明白为什么它会完全忽略EXTRA_INFO的值。
** 编辑 **TABLE_DATA和EXTRA_INFO从回调函数中获取它们的api的过程是这样的。
const TABLE_DATA = backend_route('/tableinfo')
const backend_route = (route) => {
const backend = 'http://127.0.0.1:5000'
return backend + route
}
问题出在我的提交获取方法上。'方法'而不是 '方法'.
我真傻。但我觉得很奇怪,反应如何回应该错误。