将bing搜索嵌入到nodejs中

时间:2013-12-01 06:32:23

标签: node.js express bing-api

我想将bing搜索嵌入Nodejs,我阅读了文档a link。然而,该方法是关于PHP,我找不到关于如何在nodejs中使用bing搜索的教程。(我是新手,我不熟悉php。我试图将php代码转换为nodejs而且我失败了因为有很多这两者之间的差异)

假设我有这样的bing.ejs:

<html>
 <head>
  <title>Bing Search Tester (Basic)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 </head>
 <body>
  <h1>Bing Search Tester (Basic)</h1>
  <form  method="POST" action="/bing">
   <label for="service_op">Service Operation</label><br/>
   <input name="service_op" type="radio" value="Web" CHECKED /> Web
   <input name="service_op" type="radio" value="Image" /> Image
   <br/>
   <label for="query">Query</label><br/>
   <input name="query" type="text" size="60" maxlength="60" value="" /><br /><br />
   <input name="bt_search" type="submit" value="Search" />
  </form>
  <h2>Results</h1>
 {RESULTS}
 </body>
</html>

如何在

中编写代码
app.post('/bing', function(req, res) {
    var service_op = req.body.service_op;
    var query = req.body.query;
            //something to add...
});

接下来我应该写些什么?或者任何人都可以给我一个模板? THX!

2 个答案:

答案 0 :(得分:4)

这对我有用:

// this somewhere at the top of your code:
var acctKey = 'YourAPIKey';
var rootUri = 'https://api.datamarket.azure.com/Bing/Search';
var auth    = new Buffer([ acctKey, acctKey ].join(':')).toString('base64');
var request = require('request').defaults({
  headers : {
    'Authorization' : 'Basic ' + auth
  }
});

// here's how to perform a query:
app.post('/bing', function(req, res) {
  var service_op  = req.body.service_op;
  var query       = req.body.query;
  request.get({
    url : rootUri + '/' + service_op,
    qs  : {
      $format : 'json',
      Query   : "'" + query + "'", // the single quotes are required!
    }
  }, function(err, response, body) {
    if (err)
      return res.send(500, err.message);
    if (response.statusCode !== 200)
      return res.send(500, response.body);
    var results = JSON.parse(response.body);
    res.send(results.d.results);
  });
});

此代码使用request模块,因此请先安装:

$ npm install request

答案 1 :(得分:1)

您可以使用封装请求的this module,以便您可以使用它 像:

var Bing = require('node-bing-api')({ accKey: "your-account-key" });

Bing.web(req.body.query, function(error, res, body){
    console.log(body);
  },
  {
    top: 50,
    market: 'en-US' 
  });

它适用于Azure版本。您只需更换帐户密钥。