我试图使用必应搜索API来返回一个JSON字符串。我第一次使用下面的网址按Azure的探索网站(https://datamarket.azure.com/dataset/explore/5BA839F1-12CE-4CCE-BF57-A49D98D29A44)尝试:node.js http和bing搜索API
'https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27NGI%20SPA%27&Market=%27en-US%27'
后,我发现了一个SO线程Using the new Bing API (nodejs)其中建议我用以下形式的网址:
https://user:<YourDefaultAccountKey>@api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27leo%20fender%27&Market=%27en-US%27&$top=50&$format=JSON
两者的这些返回状态401(身份验证失败):
STATUS: 401
HEADERS: {"content-type":"application/json; charset=utf-8","server":"Microsoft-IIS/8.0","jsonerror":"true","x-powered-by":"ASP.NET","access-control-allow-origin":"*","access-control-allow-credentials":"false","access-control-allow-headers":"Authorization, DataServiceVersion, MaxDataServiceVersion","access-control-expose-headers":"DataServiceVersion, MaxDataServiceVersion","access-control-allow-methods":"GET, POST, OPTIONS","access-control-max-age":"604800","date":"Wed, 02 Jul 2014 17:23:29 GMT","content-length":"91"}
BODY: {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
我也尝试过其他各种URL组合,无济于事。我的代码如下:
var url = require('url');
var http = require('http');
var serviceRootURL = 'https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27NGI%20SPA%27&Market=%27en-US%27'
var params = 'hi';
var dataURL = url.parse(serviceRootURL);
var post_options = {
hostname: dataURL.hostname,
port: dataURL.port || 80,
path: dataURL.path,
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': params.length
}
};
var req = http.request(post_options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
任何想法为什么我得到认证失败?
是否有前端模块而不是节点? –
我不建议从前端使用它,因为您需要将访问密钥也放在前端,这意味着安全问题。如果你仍然想这样做,我想你可以使用browserify,但我从来没有尝试过。 –