击中 Google 视觉 Api 时出错

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()

我正在尝试使用 google 视觉功能之一,即文本检测。但是每当我点击 api 时,我都会收到此错误。我仔细检查了 url 和其他数据。

{ 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 }

尝试将请求修改为:

  const options = {
  method: 'POST',
  headers: {
    'Content-Type' : 'application/json'
  }
};

const req = http.request(`https://vision.googleapis.com/v1/images:annotate?key=<some key>`, options, (res : any) => {
  res.on('data', (chunk : any) => {
    console.log(`BODY: ${chunk}`);
  });
});

因为 https://vision.googleapis.com/v1/images:annotate?key=<some key> 是完整的 URL,不是有效的主机名。

这段代码应该可以工作,只需要做几处更改,例如,我们将使用 https 模块而不是 http 模块。

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()