javascript - React/Express:在响应承诺中插入 if 语句?
问题描述
我收到了从 POST 调用到 express 后端的承诺响应。我想在承诺中插入一个 if 语句,这似乎打破了它。
这有效:
fetch('http://localhost:8000/upload', {
method: 'POST',
body: formData,
})
.then(response =>
response.json())
.then(response => {
console.log(response);
})
这个 if else 语句破坏了代码:
fetch('http://localhost:8000/upload', {
method: 'POST',
body: formData,
})
.then(response => {
if (response.ok) {
response.json()
} else {
throw new Error('Something went wrong ...');
}
})
.then(response => {
console.log(response);
})
这样的事情可能吗?提前致谢!
解决方案
你没有回到response.json
你的if
街区。所以,在下一个then
方法中你没有response
定义。试试这个:
fetch('http://localhost:8000/upload', {
method: 'POST',
body: formData,
})
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('Something went wrong ...');
}
})
.then(response => {
console.log(response);
})
推荐阅读
- java - Java 中的强制转换是如何工作的?
- xpath - 为什么我在 Google sheet-importxml 中使用 xpath 时得到“N/A”,但在 Chrome HTML 调试器中却没有?
- python - 在测试集上使用 statsmodels OLS
- awk - awk 部分匹配以将文本附加到文件
- javascript - GET 请求上的 Axios 百分比编码
- r - 如何使用运行函数的按钮刷新闪亮的数据表
- aws-cli - 如何使用 AWS CLI 获取特定 VPC 的 RDS 终端节点
- azure - Microsoft 集成运行时配置管理器无法连接到数据库。错误消息:错误的 JSON 转义序列:
- sql - 是否可以删除和组合部分重复项
- python - 如何添加浮动?