【发布时间】:2019-02-26 14:05:52
【问题描述】:
我正在做一个示例 ReactJS 应用程序,我正在尝试通过“RestAPI POST”发送表单数据。下面给出了代码 sn-ps,但是,它不起作用。
组件的 render() 如下所示。填写表格后,当用户单击“提交”按钮时,会调用“handleSubmit”。
render() {
return(
<button
label="Submit"
onClick={this.handleSubmit}>
Submit
</button>
}
'handleSubmit' 的定义如下所示,此处错误为 “Uncaught TypeError: Cannot read property 'fetch' of undefined”。
handleSubmit() {
this.fetch('https://example.domain.com/api/v1/task/actual', {
method: 'POST',
body: JSON.stringify({
first_name: this.state.first_name,
last_name: this.state.last_name
})
}).then(res => console.log('Success:', JSON.stringify(res)))
.catch(error => console.error('Error:', error));
}
为了清楚起见,我也分享了 fetch 的定义。访问令牌很好。它适用于其他组件。
fetch(url, options) {
const accessToken = 'Bearer ' + auth.getAccessToken();
const headers = {
'Content-Type': 'application/json',
'Authorization' : accessToken
}
return fetch(url, {
headers,
...options
})
}
我错过了一些东西,我无法弄清楚。请多多指教。
【问题讨论】:
-
完整的绑定技术列表:stackoverflow.com/questions/34139215/…
标签: javascript reactjs rest