3

I want to save req(Request) data in app.get('/') to something. It occurred "TypeError: Converting circular structure to JSON"

var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: false}))
app.get('/', (req, res) => {
   var string = JSON.stringify(req);
   saveRequest(string)
   res.send("OK")
})
function saveRequest(){
    //...
}

Did you know req data to string? I've already try this code

app.get('/', (req, res) => {

   var string = objToString(req);
   saveRequest(string)
   res.send("OK")

})
function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}

it occurred "TypeError: Cannot convert object to primitive value"

1 Answer 1

7

I'm not sure why you'd want to save the whole request object but there are node modules available to safely stringify objects that contain circular references such as json-stringify-safe.

Heres an example

let app = require('express')();
let port = process.env.PORT || 3000;
let stringify = require('json-stringify-safe');

app.get('/', (req, res) => {
    console.log(stringify(req));
    res.send("Ok");
})

app.listen(port, () => {
    console.log("Listening on " + port);
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.