首页 > 解决方案 > 如何使用通过 POST 发送的信息显示为消息?

问题描述

我的目标是让这些错误显示在前端,我该怎么做呢?

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

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)
    } 
})

标签: node.jsexpresspost

解决方案


正如您所提到的,这个问题与您的前端有关,而不是您的后端。您在应用程序中显示这些错误的方式取决于您在前端使用的语言。你在使用 HTML、vanilla JavaScript、React、Vue 还是其他东西?根据您的回答,处理来自 Node 服务的响应的方式会有所不同。您可能希望从问题中删除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 。

如果您想知道awaitand async,这里还有一个页面:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 。


推荐阅读