【发布时间】:2018-02-11 08:53:30
【问题描述】:
我需要在我的 API 上发布一些内容。 我有这个可以正常工作的功能:
TradeContainer.js:
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
.then(data => console.log(data))
}
我想将 fetch() 移动到另一个文件,从该文件中进行所有 API 调用。在那个文件中,我已经有几个获取函数(使用 get 方法)并且它们工作正常。 但是当我将这个带有 post 方法的 fetch() 移动到该文件时,我得到一个错误:
TypeError: 无法读取未定义的属性“then”
我的代码:
TradeContainer.js:
import { saveAction } from '../components/apiCalls.js'
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
//this is fetch() function that i moved to apiCalls.js file.
//And this two lines of code throw an error.
saveAction(actionInfo)
.then(data => console.log(data))
}
apiCalls.js
export function saveAction(actionInfo){
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
}
.then(res => res.json()) 返回“ok”和 200。 但 saveAction(actionInfo) 返回 undefined。怎么会?
【问题讨论】:
-
saveAction不返回任何内容。 -
你需要返回调用返回的promise
标签: javascript jquery reactjs promise es6-promise