Zaid Humayun Zaid Humayun - 1 year ago 63
Node.js Question

How do I pass a req.setHeaders method on res.redirect method within the same app.get function?

var express = require('express');
var app = express();

var PORT = process.env.PORT;

app.get('/', function(req, res){
res.json('Enter your query parameters for an image search like so: and for the latest search results enter the url ttps://*');

Here is the app.get method where I want to get parameters input by the user and then redirect it to the bing api to return search results for an image search. The big api requires an API key to be passed into the header, like so Ocp-Apim-Subscription-Key: ••••••••••••••••••••••••••••••••.
How do I do this?

app.get('/imagesearch/:image*', function(req, res){

app.listen(PORT, function(){
console.log('Express listening on: '+PORT);

Answer Source

Since it now sounds like you just want to fetch the data from the remote site and then return it as the response to the original request, you can do that by using the request module and then piping the response from that as your response to the original http request.

const request = require('request');

app.get('/imagesearch/:image*', function(req, res){
    let options = {
        url: ''+req.params.image+'&count='+req.query.count,
        headers: {"Ocp-Apim-Subscription-Key": "xxxxx"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download