简体   繁体   English

在你的控制器中发出一个 HTTP 请求——sails.js

[英]Make a HTTP request in your Controller - sails.js

Is it possible to make a request in the controller?是否可以在控制器中提出请求? I have tried using the node.js http module but didn't have any succes.我曾尝试使用 node.js http 模块,但没有任何成功。 Is there any other method to do this?有没有其他方法可以做到这一点?

Ok, I managed to solve this using another module 'request'.好的,我设法使用另一个模块“请求”解决了这个问题。 What I did:我做了什么:

Install the module in your project:在你的项目中安装模块:

npm install -S request

And in you code you should have:在你的代码中你应该有:

 var request = require('request'); request.get({ url: <your url> }, function(error, response, body) { if (error) { sails.log.error(error); } else { sails.log.info(response); sails.log.info(body); } });

For people coming from the future, request package has fully deprecated since Feb 11th, 2020.对于来自未来的人们,自 2020 年 2 月 11 日起,请求包已完全弃用。

The alternative choices that request has recommended can be found as following.请求推荐的替代选择如下。

+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|    Package Name   | Bundle Size | API Style             | Summary                                                                                                                                                                                                    |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| node-fetch        | 0.4kb       | promise / stream      | A light-weight module that brings window.fetch to Node.js                                                                                                                                                  |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| bent              | 1kb         | fp / promise / stream | Functional HTTP client w/ async/await                                                                                                                                                                      |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| got               | 48.4kb      | promise / stream      | Simplified HTTP requests                                                                                                                                                                                   |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| make-fetch-happen | 442kb       | promise / stream      | make-fetch-happen is a Node.js library that wraps node-fetch-npm with additional features node-fetch doesn’t intend to include, including HTTP Cache support, request pooling, proxies, retries, and more! |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| axios             | 11.9kb      | promise / stream      | Promise based HTTP client for the browser and node.js                                                                                                                                                      |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| unfetch           | 1kb         | promise / stream      | Tiny 500b fetch “barely-polyfill”                                                                                                                                                                          |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| superagent        | 18kb        | chaining / promise    | Small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features                                                                    |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tiny-json-http    | 22kb        | promise               | Minimalist HTTP client for GET and POSTing JSON payloads                                                                                                                                                   |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| needle            | 164kb       | chaining / promise    | The leanest and most handsome HTTP client in the Nodelands                                                                                                                                                 |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| urllib            | 816kb       | callback / promise    | Help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.                                                                                   |
+-------------------+-------------+-----------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

I wrap node's native https.get (or http.get) in a promise and call from controller like so:我将节点的本机 https.get(或 http.get)包装在一个承诺中,并从控制器调用,如下所示:

const https = require('https')

// wrap node's https.get stream call as a promise
// note: assumes utf-8 encoded data payload to get.
async function getdata(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      res.setEncoding('utf8');
      let data = '';
      res.on('data', (chunk) => {
        data = data + chunk;
      });
      res.on('end', () => {
        resolve(data);
      })
    }).on('error', (e) => {
      reject(e);
    });
  });
}


// Call from sails controller
module.exports = {
  myaction: async function(req, res) {
    let data;
    try {
      data = await getdata('https://example.com/index.html');
    } catch (e) {
      // handle it
    }    
  ...
  }
}

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

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