The error "converting circular structure to json" occurred when trying to create a JSON web token, resulting in an unhandled TypeError

screenshot of error I recently encountered an issue while implementing JSON web token authentication on my application. The error message displayed was:

" Unhandled rejection TypeError: converting circular structure to JSON "

Upon further investigation, I found that this error occurred during the webtoken generation process, as the error disappeared when I commented out that specific section of the code.

Here is the snippet of the code in question:

    const express= require("express");
    const router= express.Router();
    let Users = require("../models/users");
    const jwt= require("jsonwebtoken");
    const configuration = require("../config");
    const app = express();
    app.set("superSecret", configuration.secret);

    //registered user submitting signin form
    router.post("/users/signin", function(req, res, next){
      let confirm;
      Users.findOne({
        where:{ username: req.body.username}
      }).then(user => {
        if(!user){
          res.send("No such users found!")
        }
        else if(user){
           confirmed = user.password === req.body.password;
          if(confirmed){
            let token = jwt.sign(user, app.get("superSecret"), 
                {expiresIn: 1440}); 
                    //expiresInMinutes
                res.json({
                            success: true,
                            message: "enjoy your json",
                            token: token
                          })
          }
          else{
            res.send('incorrect password');
          }
        }
      })
    });

Removing the let token = jwt.sign(user, app.get("superSecret).. section eliminates the errors. Thank you for any assistance provided.

Below is the snippet of my Users model:

    const Sequelize= require('sequelize')
    const bcrypt = require('bcrypt-nodejs')
    const sequelStorage = new Sequelize('newtrial', 'olatunji', '5432', {
      host: 'localhost',
      dialect: 'postgres',

        pool: {
        max: 5,
        min: 0,
        idle: 10000
      },

    });


    let Users = sequelStorage.define('users', {
      username:{
        type: Sequelize.STRING,
        allowNull: false
      },
      email: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
        validate: { isEmail: true}
      },
      password:{
        type: Sequelize.STRING,
        allowNull:false
      },
      admin:{
        type: Sequelize.BOOLEAN,
        allowNull: false,
        default: false
      }
    })

    sequelStorage.sync()
   [enter image description here][1] .catch(function(error){
      console.log(error);
    });

    module.exports= Users;

Answer â„–1

There seems to be an issue with converting the payload (the user object) into a string at this specific line in a nested dependency.

In any case, this problem may be related to how sequelize handles entity wrapping. Try using the following method instead:

let token = jwt.sign(user.toJSON(), app.get("superSecret"), {expiresIn: 1440});

For additional ways to retrieve a plain object from a sequelize model, you can refer to this question: Sequelize, convert entity to plain object

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

CodeIgniter 3 fails to handle jQuery ajax calls

I am currently tackling an ajax request issue in CodeIgniter 3. The task involves clicking on a checkbox to trigger the changVisib() function. Upon reviewing the code snippet, everything appears to be functioning correctly as the alert() is being executed. ...

Error: selenium web driver java cannot locate tinyMCE

driver.switchTo().frame("tinymce_iframe"); String script="var editor=tinyMCE.get('tinymce_textarea');"; JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript(script); I'm encountering a WebDriverException while try ...

Troubleshooting Java JSON Parsing

I am struggling with this code: public void villageData() throws JSONException{ HashMap<String, Object> villageData = new HashMap<String, Object>(); villageData.put("newShopTraps", obj.get("newShopTraps")); villageData. ...

Implementing ID-based filtering for an array of objects with React

Struggling with filtering an object in an array of objects by its ID using React. Here's the scenario: The app is a Notes app that stores each note with its Title, Text, and created date, utilizing the ID as the key. Currently, I'm working on c ...

changing the breadcrumb item to a dropdown item in a dynamic way

Hey there, I'm currently working on creating a breadcrumb item using Angular. Here is what I have so far: https://i.stack.imgur.com/zt5yX.png I decided to add a dropdown for the breadcrumb item, but I'm facing a challenge: I want to be able to ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...

Phaser3 encountering issues while loading files from Multiatlas

Attempting to utilize the multiatlas functionality in Phaser alongside TexturePacker. Encountering this issue: VM32201:1 GET http://localhost:8080/bg-sd.json 404 (Not Found) Texture.js:250 Texture.frame missing: 1/1.png The JSON file can actually be fou ...

What causes TypeScript to generate an error when using two array of object types, but not when using the shape of both?

There are two basic types of data available: type DataA = { percent: string; exchange: string; }; type DataB = { price: number; exchange: string; }; I'm puzzled as to why TypeScript gives errors when I try to use both types together: const ...

The server-side script using CURL is unable to receive the posted values

My application utilizes php and CURL for sending data to a server using the curl post method. I am facing an issue where the json string that is being posted contains values like "state":"jammu & Kashmir". However, when I attempt to retrieve this dat ...

Error Message: Node.js EJS 'Is Undefined'

When passing an array to an ejs template using Nodejs, I encountered an issue where it seems we cannot directly pass an array. As a workaround, I tried to receive the value like this: console.log(<%= val %>) The output was: Rec - 159,Rec - 160 Att ...

How can I modify the border color within a div element?

My journey into web development is just beginning, and I've grasped the basics of Java, JSP, HTML, JS, CSS, and JQ. However, I've hit a roadblock while attempting to change the border color of a div upon mouse hover. Despite my efforts, I haven&a ...

JS setTimeout not postponing execution

Attempting to introduce a delay before an AJAX call. var delay = 2000; $("#c_name").on("keyup", function() { var entered = $(this).val(); if (entered.length > 1) { setTimeout(dosearch(entered), delay) } }); Struggling to implement a d ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

PHP API for Currency Conversion

Where can I find accurate currency values in JSON or XML format? I have searched Google without success: I am looking for a free PHP solution. Any recommendations for the best option? ...

Tips for effectively grouping a JavaScript object array with the help of Lodash

I have an array of objects in JavaScript that looks like this: [{ day : "August 30th", id: 1, message : "lorem ipsum1" },{ day : "August 30th", id: 2, message : "lorem ipsum2" },{ day : "August 31th", id: 3, message : " ...

Can the geocoder API/search box be utilized to locate specific markers on a map?

Incorporating Mapbox into an Angular application with a high volume of markers on the map (potentially thousands) and hoping to implement a search box for users to easily locate specific markers based on unique names and coordinates. Is this functionalit ...

Improving communication between Components in ReactJS

I am attempting to update the state from one component to another component. I wish for the state total on header.jsx to be updated when I click on the add to cart button on product.jsx Below is my code: index.jsx // Code for index.jsx goes here head ...

How can AJAX be used for form validation prior to submission?

Currently, I am facing an issue with validation on the client side when making an ajax cross-domain request to my PHP server page. I have a standard HTML form that posts input fields such as name, last name, and message. Here is an example of my form on th ...

ReactJS is throwing an error stating that the component is undefined

Experimenting with ReactJS, I've set up a hierarchy of three nested components: UserProfile.jsx import React from 'react'; const UserProfile = React.createClass({ getInitialState: function() { return { username: "zuck" }; ...