How to convert to string from object req data in express node.js

Viewed 4053

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 Answers

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);
})
Related