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

我正在尝试使用谷歌视觉的一个功能,即文本检测。但当我碰到那个api时,我就会得到这个错误。我仔细检查了网址和其他数据。
{ 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 }

最佳答案

这段代码应该可以工作,只需要进行一些更改,例如我们将使用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()

07-27 14:38