Reputation: 161
Hi I have a function in router.js in NODEJS :
const authenticateUser = (req, res, next) => {
//something
};
When my application is running this function gets called. I need to inspect the response object. Is there any way that I can print my response object to client side i.e. browser or print in proper format of JSON which shows internal objects as well.
Upvotes: 1
Views: 1032
Reputation: 1264
I think that one way to log server message to the user browser console could be printing a script
tag and in that <script>
you have to console.log
(or console.error
) your server message
const authenticateUser = (req, res, next) => {
// ...
res.write(`<script>console.log('server log:', ${JSON.stringify(your_object)})</script>`)
// ...
// res.end();
};
Of course you can enclose the logging part in a function or a template literal or, even better, a class with a template literal method
ie
// any-file.mjs
// log messages to the browser console
class BrowserLogger {
constructor({method = "log", ...tail}) {
Object.assign(this, {method, ...tail})
}
// template literal
print(strings, ...args) {
// joins arguments
var all = strings.flatMap( (s, i) => [s, args[i]])
// print on the browser console
return `<script>console.${this.method}(${
all.map(this.handler.bind(this))
})</script>`
}
handler(current){
return JSON.stringify(current)
}
}
// crete a few instances of the BrowserLogger class
// one for generic messages
const logger = new BrowserLogger({})
// one for errors
const errorLogger = new BrowserLogger({
method: "error",
// custom handler for errors :)
handler(e){
return this.constructor.prototype.handler(e instanceof Error ? e.stack : e)
}
})
var obj = {foo:"bar"}
const authenticateUser = (req, res, next) => {
// ...
// generic messages
res.write(logger.print `obj:${obj}, msg:${{ foobar: true }}`)
// error
res.write(errorLogger.print `${
new Error("error message from the server!")
}`)
// ...
res.end();
};
// use authenticateUser in a server
import http from "http"
var port = 8080
var server = http.createServer(authenticateUser)
server.listen(port);
Upvotes: 0
Reputation: 2375
Use res.send(your_object)
. It will send the response to the browser.
Upvotes: 1