从应用脚本提交 Bing API 搜索请求时出现问题

问题描述 投票:0回答:1

我正在 google apps 脚本中实现 bing api 搜索。

我尝试过这种方法:

var url =https://api.bing.microsoft.com/v7.0/search?key=[appkey]&q=Bart's%20Heating%20%26%20Air var 响应 = UrlFetchApp.fetch(url);

这个方法:

var url = https://api.bing.microsoft.com/v7.0/search?q=Bart's%20Heating%20%26%20Air 变量选项= { '方法':'获取', '标题':{ 'Ocp-Apim-订阅密钥':apiKey } }; var response = UrlFetchApp.fetch(url, options);

在这两种情况下,我收到的错误是:“异常:https://api.bing.microsoft.com的请求失败返回代码 401。截断的服务器响应:{“error”:{“code”: "401","message":"由于订阅密钥无效或 API 端点错误,访问被拒绝。确保提供有效的密钥以进行操作...”

我的订阅处于活动状态,API 密钥是从 Azure 设置复制的,我相信端点是正确的。

知道问题可能是什么吗?

azure-cognitive-services bing-api
1个回答
0
投票

出现错误

401 - Access denied due to invalid subscription key or wrong API endpoint
,因为URL中包含实例的配置ID。

var endpoint = "https://api.bing.microsoft.com/";
 var url = endpoint + "/v7.0/custom/images/search?" + "q=" + searchTerm + "&customconfig=" + customConfigId

在 Azure 中创建 Bing 自定义搜索,复制

BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY
。您可以从此
链接
获取customConfigId

API调用如下:

export BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY="your_subscription_key_here"
 export YOUR_CUSTOM_CONFIG_ID="your_custom_config_id_here"

curl --header "Ocp-Apim-Subscription-Key: $BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY""https://api.bing.microsoft.com/v7.0/custom/search?q=car&customconfig=$YOUR_CUSTOM_CONFIG_ID&mkt=en-US"

下面是使用 Bing API 和 Axios 发出自定义搜索请求的代码。

const axios = require('axios');

const subscriptionKey = ' Your_Bing_API_subscription_key'; 
const customConfig = 'Your_custom_config_ID'; 
const query = 'car'; 
const market = 'en-US'; 

const url = `https://api.bing.microsoft.com/v7.0/custom/search?q=${encodeURIComponent(query)}&customconfig=${customConfig}&mkt=${market}`;

axios.get(url, {
    headers: {
        'Ocp-Apim-Subscription-Key': subscriptionKey
    }
})
.then(response => {
    console.log('Search Results:', response.data);
})
.catch(error => {
    if (error.response) {
        
        console.error('Error Response:', error.response.data);
        console.error('Status Code:', error.response.status);
    } else if (error.request) {
       
        console.error('Error Request:', error.request);
    } else {
       
        console.error('Error Message:', error.message);
    }
});

输出: enter image description here

请参阅此文档,了解 C# 中的 Bing 自定义搜索。此外,请检查此 git,了解有关如何将 Bing 网络搜索功能添加到您的应用程序的信息。

© www.soinside.com 2019 - 2024. All rights reserved.