简体   繁体   English

使用 Node.js 将对象转换为字符串时出现类型错误

[英]Getting type error while converting object to string using Node.js

I am getting the following error while trying to convert object to string using Node.js/JavaScript:尝试使用 Node.js/JavaScript 将对象转换为字符串时出现以下错误:

TypeError: Converting circular structure to JSON
    at Object.stringify (native)
    at exports.userlogin (/opt/lampp/htdocs/FGDP/route/route.js:11:19)
    at Layer.handle [as handle_request] (/opt/lampp/htdocs/FGDP/node_modules/express/lib/router/layer.js:95:5)
    at next (/opt/lampp/htdocs/FGDP/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/opt/lampp/htdocs/FGDP/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/opt/lampp/htdocs/FGDP/node_modules/express/lib/router/layer.js:95:5)
    at /opt/lampp/htdocs/FGDP/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/opt/lampp/htdocs/FGDP/node_modules/express/lib/router/index.js:330:12)
    at next (/opt/lampp/htdocs/FGDP/node_modules/express/lib/router/index.js:271:10)

I am providing my code below:我在下面提供我的代码:

exports.userlogin=function(req,res){
    var username=req.body.user_name;
    var password=req.body.user_pass;
    var ciphertext = CryptoJS.AES.encrypt(password, 'lexelPass');
    var pass=JSON.stringify(ciphertext);
}

Here I am getting ciphertext variables datatype is object and I need it to convert into string.在这里我得到ciphertext变量数据类型是对象,我需要将其转换为字符串。 But here I am getting this type of error.但在这里我遇到了这种类型的错误。

Object return by CryptoJS.AES.encrypt(password, 'lexelPass') statement is of Circular type. CryptoJS.AES.encrypt(password, 'lexelPass')语句返回的对象是循环类型。 Circular type are something like圆形类型类似于

 var obj = {}; obj.obj = obj;

So for tackling this thing we can utilize replacer callback function in JSON.stringify as a second parameter.所以为了解决这个问题,我们可以利用JSON.stringify中的JSON.stringify回调函数作为第二个参数。 By putting logic for discarding the circular object in replacer function.通过在替换函数中放置丢弃圆形对象的逻辑。

check syntax at MDN for replacer 检查 MDN 上的语法以获取替换器

You likely want to convert the ciphertext into a string using the WordArray.toString([encoding]) method.您可能希望使用WordArray.toString([encoding])方法将ciphertext转换为字符串。

var pass = ciphertext.toString();

If you really want to stringify the WordArray you can use util.inspect(object[, options]) which automatically replaces circular references with the string [Circular] instead of throwing an error, but keep in mind that util.inspect is specific to Node.如果你真的想对WordArray进行字符串化,你可以使用util.inspect(object[, options])它自动用字符串[Circular]替换循环引用而不是抛出错误,但请记住util.inspect特定于 Node .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM