search

Home  >  Q&A  >  body text

node.js - Save the hot request in nodejs, and use JSON.stringify(req) to report an error. How to solve it?

router.post("/login", function(req, res, next) {
    var file = "c:\a.txt"; 
    var str = JSON.stringify(req); 
    fs.appendFile(file, str, function(err){  
        if(err) {
            console.log(err);  
        } else {
            console.log("写入文件ok");  
        }
    }); 
});

Initially learning nodejs, when a request comes, I want to see how many things are in this request. I can directly use the console to print it out, but the console is too useless, so I just want to save it to notepad. When I open it with a local IDE, I get an error in JSON.stringify(req).

Here I put var str = req; which doesn’t work. If I replace it with this one, what is saved in txt is [object Object].

Please help me, God, what is the problem?

世界只因有你世界只因有你2753 days ago880

reply all(3)I'll reply

  • 为情所困

    为情所困2017-05-16 13:22:56

    req cannot be serialized into json. If you want to see what’s in it except the console, you can only use debug

    reply
    0
  • 高洛峰

    高洛峰2017-05-16 13:22:56

    req contains circular reference fields, so it cannot be stringify. Give an example

    let a = {}
    let b = {a}
    a.b = b
    JSON.stringify(a) //TypeError: Converting circular structure to JSON
    a.toString() //[Object Object]

    If you want to view req, you can view it through debugging

    router.post("/login", function(req, res, next) {
        var file = "c:\a.txt"; 
        var str = JSON.stringify(req); 
        debugger; //断点
        res.end('')
    });

    Command line debugging
    node debug <main.js>

    chrome debugging
    node --inspect <main.js>

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 13:22:56

    Wanting to see req in a file is easy.

    router.post("/login", function(req, res, next) {
        console.log(req);
    });

    You don’t need to write the file yourself at all. Just enter it directly on the command line node app.js > ./a.log , and all the contents of req will be written to the a.log file in the current working directory. Be careful to replace app.js with the one you want to run. js file

    reply
    0
  • Cancelreply