【发布时间】:2018-12-20 02:07:06
【问题描述】:
当 HTTP 状态不是 200 时,如何获取后端在前端代码中发送的 JSON 对象?
当我的后端发送 200 响应时,我可以通过这样做来显示返回的 JSON 数据:
后端
res.status(200).json({status: 'Information found'})
前端
.then(data => console.log(data.status)) // Information found
但是,当我尝试对 400 或 404 状态执行相同操作时,我无法获得返回的 JSON。
后端
res.status(404).json({error: 'No information found'});
前端
.catch(error => console.log('Error from backend', error))
结果
我第一次尝试了 error.error,但没有定义。
与 200 状态返回有什么区别?如何在前端获取从后端发送的消息?
编辑
前端
axios.post('https://firebaselink.net/getTestData', { id: orderNumber })
.then(data => console.log(data.status))
.catch(error => console.error(error))
后端
export const getTestData = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const id = req.body.id;
admin.database().ref(`data/${id}`).once('value')
.then(snapshot => {
if(snapshot) res.status(200).json({status: "Information found"})
else res.status(404).json({error: "Information not found"})
}).catch(error => res.status(500).json({error: 'Internal error}))
})
})
【问题讨论】:
-
前端promise是如何创建的?
-
答案取决于您用来发出请求的库。你在调用什么 .then() ?
-
@Hodrobond 不知道您使用的是什么浏览器,但
console.log(a)对我来说很好 -
不要破坏您的问题,但您似乎没有向响应正文添加任何无法从响应状态推断的额外信息,即 404 = "not found", 500 = "internal服务器错误”等
标签: javascript json frontend axios backend