mongoose解析http字段值

发布于:2025-06-25 ⋅ 阅读:(18) ⋅ 点赞:(0)
最近在使用mongoose开发嵌入式web后端时,会遇到要解析js前端发送过来的http消息,比如传递用户名,密码过来,后端要解析出来并判断是否登录成功。
前端http有两种组装字段的方式。
第一种是 $.ajax({
            url: '/upgradePackage',
            method: 'POST',
            dataType: 'json',
            data: { devID: $('#curDevID').val(), type: $('#moduleName').val(), packageName: selectFile.name },
            success: function(json) {
            }
        });
这个时候,参数会用=和&拼接起来,mongoose解析要用
            char szUser[32] = {0};
        mg_http_get_var(&httpReq->body, "username", szUser, sizeof(szUser));
        这种方式。
        还有一种js前端采用json的格式发送,
        fetch('/login', { 
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ username, password })
})
.then(response => response.json())
.then(data => {
    console.log('data.result = ' + data.result);
    if (data.result === 0) {
        window.location.href = '/dashboard'; 
    } else {
        alert('登录失败:用户名或密码错误!'); 
    }
})
.catch(error => console.error('Error:', error));
这个时候mongoose的解析方式要换成
struct mg_str json = mg_str(httpReq->body.buf);
        char* szUser = mg_json_get_str(json, "$.username");
        printf("username=%s\n", szUser);

之前对前端不熟悉,用mongoose解析的时候,老是不能取得正确的值,网上给出的解析一会儿是方式一,一会儿是方式二,把人都绕晕了。只有搞清楚里面的逻辑,才能清晰认识到该干什么,对于不熟悉的领域,唯一能做的就是投入时间学习。


网站公告

今日签到

点亮在社区的每一天
去签到