小编Fra*_*kie的帖子

使用 Node.js Express 检查 POST 主体请求语法和格式

我想简单地检查我的服务器在名为 '/route' 的路由上获取的 POST 请求正文的语法:

  • 检查正文的格式是否实际上是 JSON,
  • 检查正文的语法是否正确(没有缺少括号或缺少引号)。

/// 我的代码 ///

app.use(express.json());

function isJsonString(str) {
    try {
        console.log('JSON Parsing function...');
        JSON.parse(str);
    } 
    catch (e) {
        console.log("Error : " + e);
        return false;
    }
    return true;
}

app.post('/route', function(req, res) {

    var isJsonString_result = isJsonString(req.body);
    console.log(isJsonString_result);

    if(isJsonString_result === true){
        console.log('OK continue');
        res.status(200).send('ok');
    }
    else{
        console.log('Wrong body format');
        res.status(404).send('ko');
    }
})
Run Code Online (Sandbox Code Playgroud)

/// 结果 ///

以下是我使用此 JSON 从 Postman 发送 POST 请求时得到的结果(使用标头“Content-Type”:“application/json”发送):

{
  "key1": "value1",
  "key2": "value2"
}
Run Code Online (Sandbox Code Playgroud)

/// 邮递员结果 ///

/// …

post json node.js express

5
推荐指数
1
解决办法
3583
查看次数

标签 统计

express ×1

json ×1

node.js ×1

post ×1