0

I am trying to implement this library here, which generates QR codes and all other kinds of codes.

The problem I have is making a request where I have access to both req and res object, since I will need to pass these to the library. In the documentation, they are recommending

http.createServer(function(req, res) {
    // If the url does not begin /?bcid= then 404.  Otherwise, we end up
    // returning 400 on requests like favicon.ico.
    if (req.url.indexOf('/?bcid=') != 0) {
        res.writeHead(404, { 'Content-Type':'text/plain' });
        res.end('BWIPJS: Unknown request format.', 'utf8');
    } else {
        bwipjs.request(req, res); // Executes asynchronously
    }

}).listen(3030);

The problem is I already have a server created, and I simply want to call the library in a get request, without creating another server. I have tried

http.get('http://localhost:3030/?bcid=azteccode&text=thisisthetext&format=full&scale=2', (req, res) => {
  bwipjs.request(req, res); // Executes asynchronously
  }
)

which obviously didn't work as the callback only takes response as an argument.

I would like to use bare node in the implementation as this is the way my server is implemented, and I don't want to add a library (like Express) just for this scenario.

3
  • I really don't understand what you are saying. Can you please be specific. Commented Mar 23, 2020 at 17:46
  • The call to the library is done like so: bwipjs.request(req, res). Therefore, for me to make the call, I need to have access to req and res. However, in the http.get, I only have the response: http.get(url, (response) => { bwipjs(request??, response) }) Commented Mar 23, 2020 at 17:48
  • nodejs.dev/making-http-requests-with-nodejs Commented Mar 23, 2020 at 17:50

1 Answer 1

1

You are heavily misunderstanding the role of http.get

http.get is used to do HTTP GET call to that certain url. It's basically what axios or request or ajax or xhr or postman or browser does.

The url param of http.get is not route. It's literally is the url you want to hit.

If you want to handle specific route you have to do it in the http.createServer() handler itself.

Like,

http.createServer(function(req, res) {
  if (req.url.indexOf('/?bcid=') != 0) {
      //do something
  } else if (req.method == "get" && req.url.indexOf('/?bcid=') != 0){
      bwipjs.request(req, res); // Executes asynchronously
  } else {
    //do something else
  }

}).listen(3030);

Check out the req or http.IncomingMessage for available properties that you can use.

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.