Search code examples
node.jshttprequestbaidu

use node.js send request for baidu map API get wrong response?


Im trying to use node.js to send http requst and call baidu map API. my code in blow:

If you past the url and use browser directly, it will give right response in right format.

But when I use node to send request, I get problem.

var request = require('request');
  request(
    { method: 'GET',
      uri: 'http://api.map.baidu.com/place/v2/suggestion?query=beijing&region=131&output=json&ak=****hLQKu9ap9fPq5N1ExF1Kk7xe5Eah'
    }
  , function (error, response, body) {

      res.json({
        res:response
      })
    }
  )

Meanwhile, if I change the url contains some Chinese like:

http://api.map.baidu.com/place/v2/suggestion?query=北京理工大学&region=北京&output=json&ak=****hLQKu9ap9fPq5N1ExF1Kk7xe5Eah

In node.js it will give status code 400 and totally wrong response.


Solution

  • you must encode your uri with encodeURI

    uri: encodeURI('http://api.map.baidu.com/place/v2/suggestion?query=北京理工大学&region=北京&output=json&ak=3104hLQKu9ap9fPq5N1ExF1Kk7xe5Eah')