Search code examples
node.jsrequestnode-modulesasync.jssuperagent

Pass value from http.request or superagent to http.createServer NodeJs


I am not sure what the issue is but I think I have to make this async or promise based (idk how). I simply want to pass the callback to http server on res.end. Can some one help please?

HTTP Request or SuperAgent passes the value to the function below. How to send this to http.createserver ?

function receiveCallback(link) {  
    console.log(link);
    //this works fine, echos the LINK we want to 302 to
}

How to pass link to http server?

http.createServer(function (req, res) {
  res.writeHead(302, {'Location': link});
  res.end();
}).listen('8080');

Ex. User opens domain.com/test?somevar

somevar is sent to superagent which then produces a link

How to 302 the user to the link


Solution

  • If your superagent is making its own request every time the server gets a request, it would look something like this:

    const http = require('http');
    const url = require('url');
    const request = require('superagent');
    
    http.createServer((req, res) => {
    
        const queryParams = url.parse(req.url, true).query;
    
        request
            .get('/get/my/link')
            .send({ somevar: queryParams.somevar })
            .end((err, response) => {
    
                if (err)
                    throw err;
    
                const link = response.body.link;
    
                res.writeHead(302, { 'Location': link });
                res.end();
            });
    
    }).listen('8080');