Axios在前端不返回错误

时间:2018-10-24 19:38:20

标签: node.js express axios

我正在使用Axios通过 NODEJS + EXPRESS ...

在我的后端上使用API

此后,我在前端中将Axios与面向对象的 ES6 + JAVASCRIPT ...

接下来会发生什么,如果我经过API路由的后端,它将在返回时返回错误,并在返回时返回日期...

但是在我的前端中, axios捕获不起作用 因为,它使我返回了日期错误并且没有改变status和statusText

我想知道为什么会发生这种情况,并将我的后端修复为“ date”属性,它会在没有错误的情况下返回结果,并且当出现错误时,将Axios响应的“ status”和“ statusText”属性更改为前端的捕获将起作用 ..

后端控制器代码(NODEJS CONSUME API):

module.exports.consume = (app, req, res) => {
    // PARAMS && QUERYS
    const xsjs        = req.params.urn;
    const shoppingId  = req.query.Shop,
          periodOf    = req.query.PeriodOf,
          periodUntil = req.query.PeriodUntil,
          kpi         = req.query.Kpi,
          select      = req.query.Select;

    // API_DAO.JS (CLASS)
    const apiDAO = new app.models.apiDAO(xsjs, shoppingId, periodOf, periodUntil, kpi, select);
          apiDAO.getResponseAxios().then  ( response => res.json(response.data) )
                                   .catch ( error    => res.json({ ErrorStatus: error.response.status, ErrorText: error.response.statusText }) );
}

AXIOS在我的前沿

class Api {
    constructor(xsjs, shoppingId, periodOf, periodUntil, kpi, select){
        this.xsjs        = xsjs;
        this.shoppingId  = shoppingId;
        this.periodOf    = periodOf;
        this.periodUntil = periodUntil;
        this.kpi         = kpi;
        this.select      = select;
    }

    configAxios(){
        return axios.create({
            baseURL:             'http://localhost:3000/api/',
            method:              'GET',
            responseType:        'json',
            responseEncoding:    'utf8',
            headers: {
                'Content-Type':  "application/json",
                'Cache-Control': "no-cache",
            },
            params: {  
                Shop:       this.shoppingId,
                PeriodoDe:  this.periodOf,
                PeriodoAte: this.periodUntil,
                Kpi:        this.kpi,
                Select:     this.select
            }
        });
    }

    async consume(){ return await this.configAxios().get(`/${this.xsjs}?`); }
}

前端的Axios错误响应

请注意,它会在date属性中插入错误,并且不会更改date属性之外的status或statusText。 (这应该是错误的,因为后端的API查询中有错误)

img1 Axios响应,当正确执行参数和查询后

img2

1 个答案:

答案 0 :(得分:0)

问题出在library(forcats) ggplot(dataFrame, aes(x=color, y = percent, fill = fct_recode(cut, "Very\nGood"="Very Good")))+ geom_bar(stat = "identity") + geom_text(aes(label = pretty_label), position=position_fill(vjust=0.5), colour="white", size=3)+ coord_flip()+ theme(legend.position="top", legend.key.width=unit(1.2, "cm"))+ guides(fill = guide_legend(label.position = "bottom", reverse = TRUE)) + labs(fill="Cut") + scale_y_continuous(labels=percent) 回调内部。后端出现错误,但是在捕获到错误之后,您会使用默认的.catch状态代码发送正常的JSON响应:

200

如果您希望后端响应HTTP错误,则需要以其他方式设置HTTP状态代码:

.catch(error => res.json({ ErrorStatus: error.response.status, ErrorText: error.response.statusText }) );