Skip to content

Instantly share code, notes, and snippets.

@searls
Last active September 15, 2018 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searls/d65259f79b3f8f48032f3d54c492845b to your computer and use it in GitHub Desktop.
Save searls/d65259f79b3f8f48032f3d54c492845b to your computer and use it in GitHub Desktop.
I refactored the example quickstart code provided on Azure's cognitive API
// Original doc on https://docs.microsoft.com/en-us/azure/cognitive-services/bing-web-search/quickstarts/nodejs#make-a-request-and-print-the-response
// This will not run because the doc's ordering led me to call an undefined method
// Use strict mode.
'use strict';
// Require the https module.
let https = require('https');
// Replace with a valid subscription key.
let subscriptionKey = 'enter key here';
/*
* Verify the endpoint URI. If you
* encounter unexpected authorization errors, double-check this host against
* the endpoint for your Bing Web search instance in your Azure dashboard.
*/
let host = 'api.cognitive.microsoft.com';
let path = '/bing/v7.0/search';
let term = 'Microsoft Cognitive Services';
// Validate the subscription key.
if (subscriptionKey.length === 32) {
bing_web_search(term);
} else {
console.log('Invalid Bing Search API subscription key!');
console.log('Please paste yours into the source code.');
}
let response_handler = function (response) {
let body = '';
response.on('data', function (d) {
body += d;
});
response.on('end', function () {
console.log('\nRelevant Headers:\n');
for (var header in response.headers)
// Headers are lowercased by Node.js.
if (header.startsWith("bingapis-") || header.startsWith("x-msedge-"))
console.log(header + ": " + response.headers[header]);
// Stringify and parse the response body.
body = JSON.stringify(JSON.parse(body), null, ' ');
console.log('\nJSON Response:\n');
console.log(body);
});
response.on('error', function (e) {
console.log('Error: ' + e.message);
});
};
let bing_web_search = function (search) {
console.log('Searching the Web for: ' + term);
// Declare the method, hostname, path, and headers.
let request_params = {
method : 'GET',
hostname : host,
path : path + '?q=' + encodeURIComponent(search),
headers : {
'Ocp-Apim-Subscription-Key' : subscriptionKey,
}
};
// Request to the Bing Web Search API.
let req = https.request(request_params, response_handler);
req.end();
}
// Usage:
//
// node search.js "My awesome query"
//
const https = require('https')
// HOWTO: set an environment variable https://is.gd/zu55jA
const API_KEY = process.env['AZURE_API_KEY']
const API_URL = 'https://api.cognitive.microsoft.com/bing/v7.0/search'
function bingWebSearch(query) {
https.get(`${API_URL}?q=${encodeURIComponent(query)}`, {
headers: {
'Ocp-Apim-Subscription-Key': API_KEY
}
}, res => {
let body = ''
res.on('data', part => body += part)
res.on('end', () => {
for (var header in res.headers) {
if (header.startsWith("bingapis-") || header.startsWith("x-msedge-")) {
console.log(header + ": " + res.headers[header])
}
}
console.log('\nJSON Response:\n')
console.log(JSON.stringify(JSON.parse(body), null, ' '))
})
res.on('error', e => {
console.log('Error: ' + e.message)
throw e
})
})
}
const query = process.argv[2] || 'Microsoft Cognitive Services'
bingWebSearch(query)
@JoshCheek
Copy link

Signature of get was different for me. Modified it slightly and also threw an error on a missing env var. Tested it on node 6 and 10

// Usage:
//
//   node search.js "My awesome query"
//
const https = require('https')

// HOWTO: set an environment variable https://is.gd/zu55jA
const API_KEY = process.env['AZURE_API_KEY']
if (!API_KEY) {
  throw new Error('Missing the AZURE_API_KEY environment varable')
}

function bingWebSearch(query) {
  https.get({
    hostname: 'api.cognitive.microsoft.com',
    path:     '/bing/v7.0/search?q=' + encodeURIComponent(query),
    headers:  {
      'Ocp-Apim-Subscription-Key': API_KEY
    },
  }, res => {
    let body = ''
    res.on('data', part => body += part)
    res.on('end', () => {
      for (var header in res.headers) {
        if (header.startsWith("bingapis-") || header.startsWith("x-msedge-")) {
          console.log(header + ": " + res.headers[header])
        }
      }
      console.log('\nJSON Response:\n')
      console.log(JSON.stringify(JSON.parse(body), null, '  '))
    })
    res.on('error', e => {
      console.log('Error: ' + e.message)
      throw e
    })
  })
}

const query = process.argv[2] || 'Microsoft Cognitive Services'
bingWebSearch(query)

image

@searls
Copy link
Author

searls commented Sep 15, 2018

@JoshCheek - indeed, the three arg method requires Node v10.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment