Search code examples
node.jsgoogle-vision

Getting error on hitting Google Vision Api


  const options = {
  hostname: 'https://vision.googleapis.com/v1/images:annotate?key=<some key>',
  method: 'POST',
  headers: {
    'Content-Type' : 'application/json'
  }
};

const req = http.request(options, (res : any) => {
  res.on('data', (chunk : any) => {
    console.log(`BODY: ${chunk}`);
  });
});

req.on('error', (e) => {
  console.log(e)
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(JSON.stringify(body))
req.end()

I am trying to use one of the google vision feature i.e. Text Detection. But when ever I am hitting that api I am getting this error. I double checked the url and other data.

{ Error: getaddrinfo ENOTFOUND https://vision.googleapis.com/v1/images:annotate?key=<> https://vision.googleapis.
com/v1/images:annotate?key=<key>:80
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
  errno: 'ENOTFOUND',
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname:
   'https://vision.googleapis.com/v1/images:annotate?key=<key>',
  host:
   'https://vision.googleapis.com/v1/images:annotate?key=<key>',
  port: 80 }

Solution

  • This code should work, there are only a couple of changes necessary, for example we'll use the https module rather than the http module.

    const https = require('https');
    
    const options = {
        hostname: 'vision.googleapis.com',
        path: '/v1/images:annotate?key=' + API_KEY,
        method: 'POST',
        headers: {
            'Content-Type' : 'application/json'
        }
    };
    
    let data = "";
    const req = https.request(options, (res: any) => {
        res.on('data', (chunk: any) => {
            data += chunk;
        });
        res.on('end', (chunk) => {
            console.log(`BODY: ${data}`);
        });
    });
    
    req.on('error', (e) => {
        console.log(e)
        console.error(`problem with request: ${e.message}`);
    });
    
    // Write data to request body
    req.write(JSON.stringify(body))
    req.end()