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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.