a-coder
a-coder

Reputation: 23

Getting Console Messages on Webpage NodeJS

I'm wondering if there's any way to listen for console messages and act on console messages when they're received. Mainly, is there any way to do this without an external module, and using the http module?

The goal is to trigger a NodeJS function or code snippet on an event like click in the HTML. If there's also a way to do this, then that's great. But once again, I'd like to do this without an external module, and just use those that are built-in to NodeJS.

Upvotes: 2

Views: 99

Answers (2)

Quantalabs
Quantalabs

Reputation: 449

I know @Haris Wilson already got the answer, but I'd just like to provide a code example.

Instead of trying to catch a console message and then execute a function if we find it, we can use fetch() to make a request to whatever URL we need, and this can allow us to make other requests.

In this case, we can use the url module and the http module to parse the url and serve the API and website, respectively.

const url = require('url')
const http = require('http')

const requestListener = async function (req, res) {
     // Basic server setup
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });

    res.end(/** Content here */)

    // API 
    if (url.parse(req.url, true).pathname === '/APIcall') {
        let arguments = url.parse(req.url, true).query
        
        // Preform necassary actions here
    }
}

We can now use onClick to call a function inside our webpage JavaScript, and use fetch([API URL]) to give our NodeJS data to preform an action. We can use URL params to do this, such as https://localhost:8080/APIcall?data=someData&moreParam=more-data, where ?data=someData&moreParam=more-data are the URL params.

Upvotes: 0

Haris Wilson
Haris Wilson

Reputation: 166

Use onclick() function in JavaScript to trigger a function call when clicking on a element. Then use fetch to make a api call to the nodejs server.

Upvotes: 1

Related Questions