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

创建Http客户端请求获取数据,如Axios

  •  0
  • Wicak  · 技术社区  · 7 年前

    我遇到了一个问题,无法创建http请求,就像axios使用node.js一样。

    axios.get('http://url')
      .then(response => {
    
      })
      .catch(error => {
        console.log('Error fetching and parsing data', error);
      });
    

    (axios)代码中发生了什么,所以我们可以获取数据。我想在node.js中创建相同的函数,不使用三个库,也不使用fetchapi或XHR。

    我想创建一个类

    Class MyCode {
     static get(){
    //mycode stuck
     }
    }
    

    MyCode.get('url')。然后…捕获。。。。

    谢谢你

    2 回复  |  直到 7 年前
        1
  •  0
  •   R.Sarkar    7 年前

    希望这对你有帮助。

    var http=require('http');
    var req=http.request('http://url',{'method':'methodtype',headers:{'Content-Type':'text/plain'}},(res)=>{
       res.on('data',(data)=>{
         console.log(`data is ${data}`);
       });
    
    });
    req.on('error',(err)=>{
        console.log('error -->',err);
    });
    
    req.end();
    
        2
  •  0
  •   Vlad Dohotaru    6 年前

    'use strict';
    
    const defaultRequest = require('request-promise-native');
    
    class MyCode {
        constructor({
            request = defaultRequest,
        } = {}) {
            this.request = request;
        }
        async get({
            method = 'GET',
            headers = {},
            body,
            url,
            ...rest
        }) {
            try {
                return this.request(Object.assign(
                    {
                        url,
                        method,
                        headers,
                        body,
                    },
                    rest,
                ));
            } catch (e) {
                throw e;
            }
        }
    }
    
    
    async function test() {
        let x = new MyCode();
        const response = await x.get({
            url: 'https://jsonplaceholder.typicode.com/todos/1',
        });
    
        console.log(response);
    }
    
    test();
    
    推荐文章