Rychlý start: Použití Node.js k volání rozhraní API Bingu pro vyhledávání na webuQuickstart: Use Node.js to call the Bing Web Search API

V tomto rychlém startu poprvé zavoláte rozhraní API Bingu pro vyhledávání na webu a dostanete odpověď JSON, a nezabere vám to ani 10 minut.Use this quickstart to make your first call to the Bing Web Search API and receive a JSON response in less than 10 minutes.

K tomuto rychlému startu potřebujete účet služby Azure Cognitive Services s rozhraními API pro vyhledávání Bingu.This quickstart requires an Azure Cognitive Services account with Bing Search APIs. Pokud účet nemáte, můžete k získání klíče předplatného použít bezplatnou zkušební verzi.If you don't have an account, you can use the free trial to get a subscription key.

PožadavkyPrerequisites

Tady je pár věcí, které budete potřebovat na začátku tohoto rychlého startu:Here are a few things that you'll need before running this quickstart:

Vytvoření projektu a deklarace požadovaných modulůCreate a project and declare required modules

Ve svém oblíbeném integrovaném vývojovém prostředí nebo editoru vytvořte nový projekt Node.js.Create a new Node.js project in your favorite IDE or editor. Pak do svého projektu zkopírujte následující fragment kódu.Then copy the code snippet below into your project. V tomto rychlém startu se používá striktní režim, který k odesílání a přijímání dat vyžaduje modul https.This quickstart uses strict mode and requires the https module to send and receive data.

// Use strict mode.
'use strict';

// Require the https module.
let https = require('https');

Definování proměnnýchDefine variables

Abychom mohli pokračovat, musíme nastavit několik proměnných.A few variables must be set before we can continue. Ověřte, že hodnoty host a path jsou platné a nahraďte hodnotu subscriptionKey platným klíčem předplatného ze svého účtu Azure.Confirm that the host and path are valid and replace the subscriptionKey value with a valid subscription key from your Azure account. Vyhledávací dotaz můžete přizpůsobit. Stačí místo term zadat jinou hodnotu.Feel free to customize the search query by replacing the value for term.

// 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.');
}

Vytvoření obslužné rutiny odpovědiCreate a response handler

Vytvořte obslužnou rutinu, která odpověď převede na text a parsuje ji.Create a handler to stringify and parse the response. Funkce response_handler se volá při každém požadavku do rozhraní API Bingu pro vyhledávání na webu. Uvidíte to v další části.The response_handler is called each time a request is made to the Bing Web Search API, as you'll see in the next section.

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);
    });
};

Vytvoření požadavku a tisk odpovědiMake a request and print the response

Vytvořte požadavek a volejte rozhraní API Bingu pro vyhledávání na webu.Construct the request and make a call to the Bing Web Search API. Po vytvoření požadavku se volá funkce response_handler a vytiskne se odpověď.After the request is made, the response_handler function is called and the response is printed.

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();
}

Spojení všech součástí dohromadyPut it all together

Posledním krokem je spuštění kódu.The last step is to run your code! Pokud chcete porovnat svůj kód s naším, najdete ukázkový kód na GitHubu.If you'd like to compare your code with ours, sample code is available on GitHub.

Ukázková odpověďSample response

Odpovědi rozhraní API Bingu pro vyhledávání na webu se vrátí jako objekt JSON.Responses from the Bing Web Search API are returned as JSON. Ukázková odpověď je zkrácená, aby zobrazovala jenom jeden výsledek.This sample response has been truncated to show a single result.

{
  "_type": "SearchResponse",
  "queryContext": {
    "originalQuery": "Microsoft Cognitive Services"
  },
  "webPages": {
    "webSearchUrl": "https://www.bing.com/search?q=Microsoft+cognitive+services",
    "totalEstimatedMatches": 22300000,
    "value": [
      {
        "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
        "name": "Microsoft Cognitive Services",
        "url": "https://www.microsoft.com/cognitive-services",
        "displayUrl": "https://www.microsoft.com/cognitive-services",
        "snippet": "Knock down barriers between you and your ideas. Enable natural and contextual interaction with tools that augment users' experiences via the power of machine-based AI. Plug them in and bring your ideas to life.",
        "deepLinks": [
          {
            "name": "Face API",
            "url": "https://azure.microsoft.com/services/cognitive-services/face/",
            "snippet": "Add facial recognition to your applications to detect, identify, and verify faces using a Face API from Microsoft Azure. ... Cognitive Services; Face API;"
          },
          {
            "name": "Text Analytics",
            "url": "https://azure.microsoft.com/services/cognitive-services/text-analytics/",
            "snippet": "Cognitive Services; Text Analytics API; Text Analytics API . Detect sentiment, ... you agree that Microsoft may store it and use it to improve Microsoft services, ..."
          },
          {
            "name": "Computer Vision API",
            "url": "https://azure.microsoft.com/services/cognitive-services/computer-vision/",
            "snippet": "Extract the data you need from images using optical character recognition and image analytics with Computer Vision APIs from Microsoft Azure."
          },
          {
            "name": "Emotion",
            "url": "https://www.microsoft.com/cognitive-services/en-us/emotion-api",
            "snippet": "Cognitive Services Emotion API - microsoft.com"
          },
          {
            "name": "Bing Speech API",
            "url": "https://azure.microsoft.com/services/cognitive-services/speech/",
            "snippet": "Add speech recognition to your applications, including text to speech, with a speech API from Microsoft Azure. ... Cognitive Services; Bing Speech API;"
          },
          {
            "name": "Get Started for Free",
            "url": "https://azure.microsoft.com/services/cognitive-services/",
            "snippet": "Add vision, speech, language, and knowledge capabilities to your applications using intelligence APIs and SDKs from Cognitive Services."
          }
        ]
      }
    ]
  },
  "relatedSearches": {
    "id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches",
    "value": [
      {
        "text": "microsoft bot framework",
        "displayText": "microsoft bot framework",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+bot+framework"
      },
      {
        "text": "microsoft cognitive services youtube",
        "displayText": "microsoft cognitive services youtube",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+youtube"
      },
      {
        "text": "microsoft cognitive services search api",
        "displayText": "microsoft cognitive services search api",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+search+api"
      },
      {
        "text": "microsoft cognitive services news",
        "displayText": "microsoft cognitive services news",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+news"
      },
      {
        "text": "ms cognitive service",
        "displayText": "ms cognitive service",
        "webSearchUrl": "https://www.bing.com/search?q=ms+cognitive+service"
      },
      {
        "text": "microsoft cognitive services text analytics",
        "displayText": "microsoft cognitive services text analytics",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+text+analytics"
      },
      {
        "text": "microsoft cognitive services toolkit",
        "displayText": "microsoft cognitive services toolkit",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+toolkit"
      },
      {
        "text": "microsoft cognitive services api",
        "displayText": "microsoft cognitive services api",
        "webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+api"
      }
    ]
  },
  "rankingResponse": {
    "mainline": {
      "items": [
        {
          "answerType": "WebPages",
          "resultIndex": 0,
          "value": {
            "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0"
          }
        }
      ]
    },
    "sidebar": {
      "items": [
        {
          "answerType": "RelatedSearches",
          "value": {
            "id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches"
          }
        }
      ]
    }
  }
}

Další krokyNext steps

Viz takéSee also