代码之家  ›  专栏  ›  技术社区  ›  user2828442

从NodeJS向restapi发出请求

  •  0
  • user2828442  · 技术社区  · 5 年前

    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);
    });
    }
    

    Uncaught ReferenceError: require is not defined

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

    0 回复  |  直到 5 年前
        1
  •  2
  •   jed    5 年前

    如果您在浏览器中运行这个,您可以在postman中选择“JavaScript Fetch”代码选项,而不是“nodejs request”选项。不能直接在浏览器中使用nodejs。 邮递员会给你的代码看起来更像这样,但有更多的细节,没有'要求':

    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));
    
    推荐文章