如何使用通过POST发送的信息显示为消息?

时间:2019-11-30 15:14:25

标签: node.js express post

My goal is to get those errors to display on the front end, how might I go about doing this?

这是我在应用程序级别上的代码:

app.post('/register', 
[
    check('username').notEmpty(),
    check('password')
    .notEmpty()
    .custom((value,{req, loc, path}) => {
        if (value !== req.body.password2) {
            // throw error if passwords do not match
            throw new Error("Passwords don't match");
        } else {
            return value;
        }
    }),
    check('email').isEmail(),
    check('email').notEmpty(),

], function (req,res ){
    const errors = validationResult(req);
    if (!errors.isEmpty()){
        return res.json({errors: errors.array()});
    }
    else{
        User.create({
            username: req.body.username,
            password: req.body.password,
            email: req.body.email,
            name: req.body.name,
        })
        console.log(req.body.password, req.body.password2)
    } 
})

1 个答案:

答案 0 :(得分:0)

正如您所提到的,这个问题与您的前端有关,而不与您的后端有关。在应用程序中显示这些错误的方式取决于前端使用的语言。您在使用HTML,原始JavaScript,React,Vue还是其他工具?根据您的答案,处理来自节点服务的响应的方法将有所不同。您可能要从问题中删除node.jsexpresspost标记,然后适当地重新标记。

话虽如此,我可以肯定地说,鉴于您共享的屏幕快照中请求的“预览”标签中的内容,您将必须在msg中获得errors的值响应数组。为此,您可能需要使用某种JSON解码器/编码器。

如果您使用的是JavaScript,则处理这些错误消息的可能方法如下所示:

const URL_OF_ENDPOINT = 'URL_OF_ENDPOINT'; // change this value

async function sendRequest(payload) {
    try {
        const response = await fetch(URL_OF_ENDPOINT, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        const json = await response.json(); // the JSON decoder
        if (json.errors && json.errors.length > 0) {
            const errorMessages = json.errors.map(error => error.msg); // loop through the array of errors and return the message
            console.error({ errorMessages });
            return { error: errorMessages }; // you can use 'error' to display a message on the page
        } else {
            console.log('No error message found.');
            return { json }; // you can use 'json' to display something that is not an error
        }
    } catch (error) {
        console.error('Oops! Something went wrong.', { error });
        return  { error }; // you can use 'error' to display a message on the page
    }
}

async function handleRequest() {
    const payload = { name: 'John', username: 'john', email: 'john@doe.com', password: '123', passwordConfirm: 'abc' };
    const parsedResponse = await sendRequest(payload);
    console.log({ parsedResponse }); // parsedResponse will have an 'error' property if there was a problem or a 'json' property if the request succeeded  
}

handleRequest();

我在这里创建了一支笔,可以在其中使用以下代码:https://codepen.io/yvesgurcan/pen/oNgvybY

如果您想进一步了解fetch,则MDN拥有出色的文档:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

如果您想了解awaitasync,这里还有一个页面:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

相关问题