目前,我正在使用node.js和socket.io进行项目。

如果想知道是否有任何方法可以自动验证客户端发送到服务器的数据。我不想通过对要在正在进行的函数中使用的每个变量使用if (!...) return;来验证数据。

例如我在server.js上有以下代码

socket.on('haveData', function(data) {
    db.query('SELECT * FROM user WHERE userid = ? LIMIT 1', [data.userid], function(errData, results, fields) {
        if (!errData && results.length) {
            ...
        }
    });
});


但是现在,如果我在浏览器的控制台中键入socket.emit('haveData');,则socket.io服务器崩溃了-当然,没有数据发出

TypeError: Cannot read property 'userid' of undefined

最佳答案

您可以使用Joi https://github.com/hapijs/joi

Joi允许您定义输入数据的架构,并使用Joi.validate方法对其进行验证(示例:https://github.com/hapijs/joi#example)。

Socket.on('event',function(data,callback){})接受回调函数,可用于将错误消息传递回客户端。

示例代码:

const Joi = require('joi');

socket.on('data',function(data,callback){

    const schema = Joi.object().keys({
        userid : Joi.string().trim().required()
    })

    Joi.validate(data, schema, function (err, value) {
        if(err){
            //Error will be sent back to the client who emitted the event
            callback(err)
        }else{
            //Do  your stuff
        }
    })
})

关于javascript - Socket.io-如果“客户端”发出错误数据,防止服务器崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47349402/

10-12 12:32
查看更多