如何使用node.js为http状态代码

时间:2017-12-11 17:58:31

标签: node.js react-native react-redux

我正在使用node.js进行基于rest的api进行用户身份验证。我想发送一个更具描述性的自定义错误消息,如“用户名/密码组合不正确”。在演示方面,我使用fetch和redux-saga做出反应原生。

这是用于将用户名/密码发送到其余层并收到返回的http错误消息的redux-saga代码:

export const login = ({userName, password}) => {
    return fetch(globals.BASE_URL + `/api/login`, {
        method  : 'POST',
        headers : {
            'Accept'        : 'application/json',
            'Content-Type'  : 'application/json'
        },
        body: JSON.stringify({
            userName: userName,
            password: password
        })
    });
}

const fetchLoginStatus = function* (action) {
    const response = yield call(login, action);

    try {
        if (response.status >= 200 && response.status < 300) {
            const userInfo = yield response.json();

            yield put({type: LOGIN_SUCCESS, authToken: userInfo.authToken});
        } else {
            yield put({type: ERROR_MESSAGE_OCCURRED, errorMessage: response.statusText});
        }
    } catch (error) {
        yield put({type: ERROR_MESSAGE_OCCURRED, errorMessage: error});
    }
}

这是用于返回错误消息的node.js代码:

app.use(function (err: Error, req: express.Request, res: express.Response, next: express.NextFunction) {
if (err instanceof IncorrectLoginError) {
    //Tried this approach initially, did not work either
    //res.statusMessage = err.message;
    //res.status(400).end();

    res.status(400).json({
        error: err.message
    });
} else {
    return res.end();
}
});

这是问题,当我从模拟器运行调试器并检查从fetch调用返回的响应对象时,我不断在响应对象中获得以下内容:

Response {
        type: 'default',
            status: 400,
            ok: false,
            statusText: undefined,
            headers:
        Headers {
            map:
            { 'x-frame-options': [Object],
                'strict-transport-security': [Object],
                connection: [Object],
                'x-dns-prefetch-control': [Object],
                date: [Object],
                'x-content-type-options': [Object],
                'content-length': [Object],
                'x-download-options': [Object],
                vary: [Object],
                'x-xss-protection': [Object],
                'content-type': [Object] } },
        url: 'http://localhost:3000/api/login',
            _bodyInit: 'Bad Request',
            _bodyText: 'Bad Request' }

最终,我想设置与statusCode一起使用但不起作用的statusText。对于第二种方法,我尝试使用返回对象传递错误字符串,但是查看Response对象,这也是无效的。设置statusCode附带的statusText的正确方法是什么?

以下是从Web Storm上的“测试RESTful Web服务”运行时显示的错误消息:

enter image description here

0 个答案:

没有答案