node.js - NodeJs POST 请求 ER_DATA_TOO_LONG

标签 node.js post request

我正在尝试向网站添加发布请求,但我不明白收到的错误。我发送了四个文本元素,我确信它们是正确的(大小、类型),并且我成功地在我的数据库中手动添加了一个元素。这不是我的网站,我真的不知道它是如何工作的,所以我复制了另一个请求。然而,错误是说我的一个元素太长,但事实并非如此,所以我有点困惑。

这是我的 POST 请求

app.post("/api/addOS" , function(req, res) {
    if(!(apikeys[req.query.username]===req.query.apikey) || (req.query.username == undefined) || (req.query.apikey == undefined)) {
        res.json({"error" : "not allowed"});
    } else {
        var con = new Database();
        var query = "INSERT INTO BRAND (name,abbr,color,type) VALUES ('"+req.body.name+"','"+req.body.abbr+"','"+req.body.couleur+"','"+req.body.type+"')";
        con.query(query).then(rows => {          
            res.json(rows);
        });
    }
});

数据库类定义如下

class Database {
constructor(  ) {
    this.connection = mysql.createConnection( {
      host: "localhost",
      user: "root",
      password: "pswd",
      database: "dbname"
  } );
}
query( sql, args ) {
    return new Promise( ( resolve, reject ) => {
        this.connection.query( sql, args, ( err, rows ) => {
            if ( err ){
                return reject( err );
            }
            resolve( rows );
        } );
    } );
}
close() {
    return new Promise( ( resolve, reject ) => {
        this.connection.end( err => {
            if ( err )
                return reject( err );
            resolve();
        } );
    } );
}

}

我的网页控制台上显示的错误是这个

angular.js:14525 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"https://localhost:4443/api/addOS?username=test&apikey=z4oP>3Jocv","headers":{"Accept":"application/json, text/plain, /"},"name":"testtest","abbr":"test","type":"os","couleur":"tre"},"statusText":""}

我的控制台上就是这个

(node:15728) UnhandledPromiseRejectionWarning: Error: ER_DATA_TOO_LONG: Data too long for column 'abbr' at row 1 at Query.Sequence._packetToError (C:\wamp64\www\node\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14) at Query.ErrorPacket (C:\wamp64\www\node\node_modules\mysql\lib\protocol\sequences\Query.js:77:18) at Protocol._parsePacket (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Protocol.js:291:23) at Parser._parsePacket (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Parser.js:433:10) at Parser.write (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Parser.js:43:10) at Protocol.write (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Protocol.js:38:16) at Socket. (C:\wamp64\www\node\node_modules\mysql\lib\Connection.js:91:28) at Socket. (C:\wamp64\www\node\node_modules\mysql\lib\Connection.js:525:10) at Socket.emit (events.js:223:5) at addChunk (_stream_readable.js:309:12) -------------------- at Protocol._enqueue (C:\wamp64\www\node\node_modules\mysql\lib\protocol\Protocol.js:144:48) at Connection.query (C:\wamp64\www\node\node_modules\mysql\lib\Connection.js:201:25) at C:\wamp64\www\node\app.js:92:29 at new Promise () at Database.query (C:\wamp64\www\node\app.js:91:16) at C:\wamp64\www\node\app.js:379:9 at Layer.handle [as handle_request] (C:\wamp64\www\node\node_modules\express\lib\router\layer.js:95:5) at next (C:\wamp64\www\node\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\wamp64\www\node\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\wamp64\www\node\node_modules\express\lib\router\layer.js:95:5) (node:15728) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:15728) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

最佳答案

我看到常见的级别问题:

1) 永远不要在请求时创建与数据库的连接。

2) 您的数据库类允许使用带参数替换的 Promise(在我的示例中为 ? 符号),因此使用它,它更安全。

您说 abbr 字段是 varchar(8),因此我的示例中的 req.body.abbr.trim() 必须清除空符号这也许就是问题所在。

请尝试此代码并告诉我结果。

const db = new Database(); // Connection must be created once

// authorization
const isAuthorized = function(req, res, next) {
  if(
   req.query.username && 
   req.query.apikey && 
   apikeys[req.query.username] === req.query.apikey
  ) {
    return next();
  }

  res.status(401).json({"error" : "not authorized"});
};

app.post(
  "/api/addOS", 
  isAuthorized,
  async function(req, res) {
    try {
      const result = await db.query(
        'INSERT INTO BRAND (name, abbr, color, type) VALUES (?, ?, ?, ?)',
        [req.body.name, req.body.abbr.trim(), req.body.color, req.body.type]
      );
      res.status(201).json(result);
    }
    catch (error) {
      res.status(500).json({message: error.message});
    }
  });

关于node.js - NodeJs POST 请求 ER_DATA_TOO_LONG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60700017/

相关文章:

node.js - PayPal REST API - RATE LIMIT REACHED 错误

node.js - Node Mysql 转义 - Mysql.Escape()/Mysql.EscapeId()

php - 如何使用 PHP 获取原始 POST 数据并保存到文件中?

mysql - 绘制 mariadb 数据库的填充演化图

python - request.endpoint的内容[:5]

python - request.session 没有将完整的 querydict 传输到另一个 View

javascript - Node.js exec 调用永远不会调用回调

javascript - 我如何使用 broccoli.js 获得一个简单的文件树来连接

javascript - 使用 json 从 ajax 请求调用的文件中获取值

post - 在 fcgi 上的 Golang 中获取 GET 请求