繁体   English   中英

从 NodeJS 向 REST API 发出请求

[英]Make a request from NodeJS to REST API

我正在测试 REST API。 它在 Postman 上运行良好。 现在我想从我的 Node 项目页面调用它。 为了实现这一点,我从 Postman 复制了其生成的代码,我在 select NodeJS NodeJS Request选项中复制了代码,如下所示:

function detect(){
var request = require("request");

var options = { method: 'POST',
  url: 'https://centralindia.api.cognitive.microsoft.com/face/v1.0/detect',
  qs: 
   { returnFaceId: 'true',
     recognitionModel: 'recognition_02',
     returnRecognitionModel: 'false',
     detectionModel: 'detection_01' },
  headers: 
   { 'postman-token': '4c4871bd-0028-5d5d-48b7-0843ews75a',
     'cache-control': 'no-cache',
     host: 'centralindia.api.cognitive.microsoft.com',
     'content-type': 'application/json',
     'ocp-apim-subscription-key': 'f890808ddc3440c0b3d51093ce12d558' },
  body: { url: 'https://i.ibb.co/34fvwYNp/sa.png' },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
}

当我运行此 function 时,我收到此错误 -

Uncaught ReferenceError: require is not defined

我如何从我的 NodeJS 页面调用这个 API?

如果您在浏览器中运行它,您可以 select postman 中的“JavaScript Fetch”代码选项而不是“nodejs 请求”选项。 您不能直接在浏览器中使用 nodejs。 Postman 将为您提供看起来更像这样但包含更多细节且没有“要求”的代码:

fetch('https://centralindia.api.cognitive.microsoft.com/face/v1.0/detect', {
  headers: {
    'content-type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM