快速入門:使用 Bing Web 搜尋 REST API 和 Node.js 來搜尋 WebQuickstart: Search the web using the Bing Web Search REST API and Node.js

使用本快速入門進行對 Bing Web 搜尋 API 第一次的呼叫,並接收 JSON 回應。Use this quickstart to make your first call to the Bing Web Search API and receive the JSON response. 這個 Node.js 應用程式會將搜尋要求傳送給 API,並顯示回應。This Node.js application sends a search request to the API, and shows the response. 雖然此應用程式是以 JavaScript 撰寫的,但 API 是一種與大多數程式設計語言都相容的 RESTful Web 服務。While this application is written in JavaScript, the API is a RESTful Web service compatible with most programming languages.

必要條件Prerequisites

以下是執行本快速入門之前的幾個必備項目:Here are a few things that you'll need before running this quickstart:

  • Node.js 6 (英文) 或更新版本Node.js 6 or later
  • 訂用帳戶金鑰A subscription key

本快速入門需要 Azure 認知服務帳戶及 Bing 搜尋 API。This quickstart requires an Azure Cognitive Services account with Bing Search APIs. 如果您還沒有帳戶,可以使用免費試用來取得訂用帳戶金鑰。If you don't have an account, you can use the free trial to get a subscription key.

建立專案,並宣告所需的模組Create a project and declare required modules

在您最愛的 IDE 或編輯器中建立新的 Node.js 專案。Create a new Node.js project in your favorite IDE or editor. 然後,將下列程式碼片段複製到您專案內名為 search.js 的檔案中。Then copy the code snippet below into your project in a file named search.js.

// Use this simple app to query the Bing Web Search API and get a JSON response.
// Usage: node search.js "your query".
const https = require('https')

設定訂用帳戶金鑰Set the subscription key

此程式碼片段會使用 AZURE_SUBSCRIPTION_KEY 環境變數來儲存您的訂用帳戶金鑰,此作法可有效避免在部署程式碼時意外洩露您的金鑰。This code snippet uses the AZURE_SUBSCRIPTION_KEY environment variable to store your subscription key, a good practice to prevent the accidental exposure of your keys when deploying code. 移至您的 API 頁面,以查閱您的訂用帳戶金鑰。Go to the Your APIs page to look up your subscription key.

如果您不熟悉環境變數的使用方式,或想要盡快執行此應用程式,您可以將 process.env['AZURE_SUBSCRIPTION_KEY'] 取代為您設定為字串的訂用帳戶金鑰。If you're unfamiliar with using environment variables, or looking to run this app as fast as possible, then you can replace process.env['AZURE_SUBSCRIPTION_KEY'] with your subscription key set as a string.

const SUBSCRIPTION_KEY = process.env['AZURE_SUBSCRIPTION_KEY']
if (!SUBSCRIPTION_KEY) {
  throw new Error('AZURE_SUBSCRIPTION_KEY is not set.')
}

建立用來提出要求的函式Create a function to make the request

此函式將提出安全的 GET 要求,將搜尋查詢儲存為路徑中的查詢參數。This function will make a secure GET request, saving the search query as a query parameter in the path. encodeURIComponent 可用來逸出無效字元,而訂用帳戶金鑰會傳入標頭中。encodeURIComponent is used to escape invalid characters, and the subscription key is passed in a header. 回呼所接收的回應會訂閱用以彙總 JSON 主體的 data 事件、會記錄任何問題的 error 事件,和可據以得知何時應將訊息視為完整的 end 事件。The callback receives a response that subscribes to the data event to aggregate the JSON body, the error event to log any issues, and the end event to know when the message should be considered complete. 完成後,應用程式會列印有關的標頭和訊息本文。When complete, the app will print the interesting headers and message body. 您可以根據自己的喜好設定來調整色彩和設定深度,深度為 1 時可適當摘要回應。You can play with the colors and set the depth to suit your preference, a depth of 1 gives a nice summary of the response.

function bingWebSearch(query) {
  https.get({
    hostname: 'api.cognitive.microsoft.com',
    path:     '/bing/v7.0/search?q=' + encodeURIComponent(query),
    headers:  { 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_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.dir(JSON.parse(body), { colors: false, depth: null })
    })
    res.on('error', e => {
      console.log('Error: ' + e.message)
      throw e
    })
  })
}

取得查詢Get the query

我們將查看程式的引數以尋找查詢。Let's look at the program's arguments to find the query. 第一個引數是節點的路徑,第二個是我們的檔案名稱,第三個是您的查詢。The first argument is the path to node, the second is our filename, and the third is your query. 如果查詢不存在,則會使用預設查詢「Microsoft 認知服務」。If the query is absent, a default query of "Microsoft Cognitive Services" is used.

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

提出要求並列印回應Make a request and print the response

現在,所有定義皆已完成,接著我們將呼叫函式!And now that everything is defined, let's call our function!

bingWebSearch(query)

組合在一起Put it all together

最後一步是執行您的程式碼:node search.js "<your query>"The last step is to run your code: node search.js "<your query>".

如果想要將您的程式碼與我們的程式碼做比較,以下是完整的程式:If you'd like to compare your code with ours, here's the complete program:

const https = require('https')
const SUBSCRIPTION_KEY = process.env['AZURE_SUBSCRIPTION_KEY']
if (!SUBSCRIPTION_KEY) {
  throw new Error('Missing the AZURE_SUBSCRIPTION_KEY environment variable')
}
function bingWebSearch(query) {
  https.get({
    hostname: 'api.cognitive.microsoft.com',
    path:     '/bing/v7.0/search?q=' + encodeURIComponent(query),
    headers:  { 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_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.dir(JSON.parse(body), { colors: false, depth: null })
    })
    res.on('error', e => {
      console.log('Error: ' + e.message)
      throw e
    })
  })
}
const query = process.argv[2] || 'Microsoft Cognitive Services'
bingWebSearch(query)

範例回應Sample response

來自 Bing Web 搜尋 API 的回應會以 JSON 格式傳回。Responses from the Bing Web Search API are returned as JSON. 本範例回應已截斷而只顯示單一結果。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/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"
          }
        }
      ]
    }
  }
}

後續步驟Next steps

另請參閱See also