JavaEar 专注于收集分享传播有价值的技术资料

TypeError: val.slice is not a function

I get this error when making a query in nodejs:

[2017-08-19 19:06:55.946] [ERROR] error - TypeError: val.slice is not a function
    at escapeString (/var/www/Bot/node_modules/sqlstring/lib/SqlString.js:183:23)
    at Object.escape (/var/www/Bot/node_modules/sqlstring/lib/SqlString.js:53:21)
    at Connection.escape (/var/www/Bot/node_modules/mysql/lib/Connection.js:270:20)

The query:

pool.query('INSERT INTO trades SET user = ' + pool.escape(row[i].csteamid) + ', tid = ' + pool.escape(makeTID) + ', status = ' + pool.escape('PendingAccept') + ', items = ' + pool.escape(Items.join('/')) + ', action = ' + pool.escape('expired') + ', code = ' + pool.escape(cod));

How can I fix this issue? I'm not using "val" or the slice function in the query.

1个回答

    最佳答案
  1. This is an indication that you have a pool.escape call with an argument that is not a string. slice is used in the implementation of that escape method.

    There are three candidate calls that could be responsible for this error:

    pool.escape(row[i].csteamid) 
    pool.escape(makeTID) 
    pool.escape(cod)
    

    Debug your code to see whether one of these is (sometimes) not a string (like null, undefined or an object, ....)

    You can force the argument to be a string like this, although that will almost certainly not give the desired result:

    pool.escape(row[i].csteamid + '') 
    pool.escape(makeTID + '') 
    pool.escape(cod + '')
    

    Better is to test the data type before you create this SQL string, with this:

    if (typeof row[i].csteamid !== 'string') throw `row[${i}].csteamid is not a string, but ${typeof row[i].csteamid}`;
    if (typeof makeTID !== 'string') throw `makeTID is not a string, but ${typeof makeTID}`;
    if (typeof cod !== 'string') throw `cod is not a string, but ${typeof cod}`;