programing

node.js에서 HTTP POST 요청은 어떻게 이루어집니까?

iphone6s 2023. 5. 22. 20:49
반응형

node.js에서 HTTP POST 요청은 어떻게 이루어집니까?

node.js에서 데이터가 있는 아웃바운드 HTTP POST 요청을 만들려면 어떻게 해야 합니까?

request이제 더 이상 사용되지 않습니다.다른 방법을 사용하는 것이 좋습니다.

특별한 순서가 없고 끔찍할 정도로 불완전합니다.

통계 비교 몇 가지 코드 예제

원답:

요청 라이브러리를 사용하면 훨씬 쉬워집니다.

var request = require('request');

request.post(
    'http://www.yoursite.com/formpage',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);

훌륭한 구문을 제공하는 것 외에도, json 요청을 쉽게 하고, oauth 서명(twitter 등)을 처리하며, 다중 파트 형식(예: 파일 업로드) 및 스트리밍을 수행할 수 있습니다.

하려면 명령을 합니다.npm install request

다음은 node.js를 사용하여 Google 컴파일러 API에 POST를 요청하는 예입니다.

// We need this to build our post string
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');

function PostCode(codestring) {
  // Build the post string from an object
  var post_data = querystring.stringify({
      'compilation_level' : 'ADVANCED_OPTIMIZATIONS',
      'output_format': 'json',
      'output_info': 'compiled_code',
        'warning_level' : 'QUIET',
        'js_code' : codestring
  });

  // An object of options to indicate where to post to
  var post_options = {
      host: 'closure-compiler.appspot.com',
      port: '80',
      path: '/compile',
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });

  // post the data
  post_req.write(post_data);
  post_req.end();

}

// This is an async file read
fs.readFile('LinkedList.js', 'utf-8', function (err, data) {
  if (err) {
    // If this were just a small part of the application, you would
    // want to handle this differently, maybe throwing an exception
    // for the caller to handle. Since the file is absolutely essential
    // to the program's functionality, we're going to exit with a fatal
    // error instead.
    console.log("FATAL An error occurred trying to read in the file: " + err);
    process.exit(-2);
  }
  // Make sure there's data before we post it
  if(data) {
    PostCode(data);
  }
  else {
    console.log("No data to post");
    process.exit(-1);
  }
});

하드코딩된 문자열 대신 파일에서 데이터를 게시하는 방법을 보여주도록 코드를 업데이트했습니다.합니다.fs.readFile성공적인 읽기 후 실제 코드를 게시하는 명령입니다.오류가 있으면 오류가 발생하고, 데이터가 없으면 프로세스가 종료되며, 오류를 나타내는 음수 값이 지정됩니다.

요청 라이브러리를 사용할 수 있습니다.https://www.npmjs.com/package/request

var request = require('request');

JSON 데이터 게시하기

var myJSONObject = { ... };
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    json: true,   // <--Very important!!!
    body: myJSONObject
}, function (error, response, body){
    console.log(response);
});

xml 데이터 게시하기

var myXMLText = '<xml>...........</xml>'
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
}, function (error, response, body){
    console.log(response);
});

편집: 2020년 2월 기준request지금까지.

간편하고 의존성이 없습니다.결과를 기다릴 수 있도록 약속을 사용합니다.응답 본문을 반환하고 응답 상태 코드를 확인하지 않습니다.

const https = require('https');

function httpsPost({body, ...options}) {
    return new Promise((resolve,reject) => {
        const req = https.request({
            method: 'POST',
            ...options,
        }, res => {
            const chunks = [];
            res.on('data', data => chunks.push(data))
            res.on('end', () => {
                let resBody = Buffer.concat(chunks);
                switch(res.headers['content-type']) {
                    case 'application/json':
                        resBody = JSON.parse(resBody);
                        break;
                }
                resolve(resBody)
            })
        })
        req.on('error',reject);
        if(body) {
            req.write(body);
        }
        req.end();
    })
}

용도:

async function main() {
    const res = await httpsPost({
        hostname: 'sentry.io',
        path: `/api/0/organizations/org/releases/${changesetId}/deploys/`,
        headers: {
            'Authorization': `Bearer ${process.env.SENTRY_AUTH_TOKEN}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            environment: isLive ? 'production' : 'demo',
        })
    })
}

main().catch(err => {
    console.log(err)
})

노드에서 HTTP POST 요청을 만드는 데 사용할 수 있는 수십 개의 오픈 소스 라이브러리가 있습니다.

Axios(권장)

const axios = require('axios');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

axios.post('https://reqres.in/api/users', data)
    .then((res) => {
        console.log(`Status: ${res.status}`);
        console.log('Body: ', res.data);
    }).catch((err) => {
        console.error(err);
    });

바늘

const needle = require('needle');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

needle('post', 'https://reqres.in/api/users', data, {json: true})
    .then((res) => {
        console.log(`Status: ${res.statusCode}`);
        console.log('Body: ', res.body);
    }).catch((err) => {
        console.error(err);
    });

요청

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    json: true,
    body: {
        name: 'John Doe',
        job: 'Content Writer'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(`Status: ${res.statusCode}`);
    console.log(body);
});

네이티브 HTTPS 모듈

const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'Content Writer'
});

const options = {
    hostname: 'reqres.in',
    path: '/api/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};


const req = https.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();

자세한 내용은 이 기사를 참조하십시오.

저는 레슬러와 니들을 생산 목적으로 사용합니다.둘 다 네이티브 httprequest보다 훨씬 강력합니다.기본 인증, 특수 헤더 입력 또는 파일 업로드/다운로드를 통해 요청할 수 있습니다.

포스트/겟 작업의 경우, httprequest를 사용하는 원시 Ajax 호출보다 훨씬 사용하기 쉽습니다.

needle.post('https://my.app.com/endpoint', {foo:'bar'}, 
    function(err, resp, body){
        console.log(body);
});

2020년 업데이트:

는 핀 - 초경량 Node.js HTTP 클라이언트를 정말 즐겼습니다.

그것은 두 가지 다른 방법으로 사용될 수 있습니다.하나는 약속(Async/Await)이 있고 다른 하나는 기존 콜백 스타일이 있습니다.

통해 :npm i phin

와 README입니다.await:

const p = require('phin')

await p({
    url: 'https://ethanent.me',
    method: 'POST',
    data: {
        hey: 'hi'
    }
})


약속되지 않은(콜백) 스타일:

const p = require('phin').unpromisified

p('https://ethanent.me', (err, res) => {
    if (!err) console.log(res.body)
})

2015년 현재 최소한의 코딩으로 이를 달성할 수 있는 다양한 라이브러리가 있습니다.저는 낮은 수준의 HTTP 자료를 절대적으로 제어할 필요가 없는 한 HTTP 요청을 위한 우아한 경량 라이브러리를 훨씬 선호합니다.

그런 도서관 중 하나가 유니레스트입니다.

설치하려면 다음을 사용합니다.npm.
$ npm install unirest

그고그위에리▁the에위▁and.Hello, World!모두에게 익숙한 예.

var unirest = require('unirest');

unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({ "Hello": "World!" })
.end(function (response) {
  console.log(response.body);
});


예:
많은 사람들이 요청의 사용을 제안하고 있습니다 [2]

주목할 만한 것은 배후에서Unirest를 사용합니다.request도서관.

Unirest는 요청 개체에 직접 액세스하는 메서드를 제공합니다.

예:

var Request = unirest.get('http://mockbin.com/request');

또한 노드를 위해 작성한 정말 멋지고 간단한 HTTP 클라이언트인 Requestify를 사용할 수 있습니다.JS + 캐싱을 지원합니다.

다음을 수행합니다.

    var requestify = require('requestify');

    requestify.post('http://example.com', {
        hello: 'world'
    })
    .then(function(response) {
        // Get the response body (JSON parsed or jQuery object for XMLs)
        response.getBody();
    });
var https = require('https');


/**
 * HOW TO Make an HTTP Call - POST
 */
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
    "message" : "The web of things is approaching, let do some tests to be ready!",
    "name" : "Test message posted with node.js",
    "caption" : "Some tests with node.js",
    "link" : "http://www.youscada.com",
    "description" : "this is a description",
    "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
    "actions" : [ {
        "name" : "youSCADA",
        "link" : "http://www.youscada.com"
    } ]
});

// prepare the header
var postheaders = {
    'Content-Type' : 'application/json',
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};

// the post options
var optionspost = {
    host : 'graph.facebook.com',
    port : 443,
    path : '/youscada/feed?access_token=your_api_key',
    method : 'POST',
    headers : postheaders
};

console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');

// do the POST call
var reqPost = https.request(optionspost, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);

    res.on('data', function(d) {
        console.info('POST result:\n');
        process.stdout.write(d);
        console.info('\n\nPOST completed');
    });
});

// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
    console.error(e);
});

이것이 제가 요청할 때 사용하는 가장 간단한 방법입니다: '요청' 모듈을 사용합니다.

'request' 모듈을 설치하는 명령:

$ npm install request

코드 예제:

var request = require('request')

var options = {
  method: 'post',
  body: postData, // Javascript object
  json: true, // Use,If you are sending JSON data
  url: url,
  headers: {
    // Specify headers, If any
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.log('Error :', err)
    return
  }
  console.log(' Body :', body)

});

Node.js의 내장된 'http' 모듈을 사용하여 요청할 수도 있습니다.

Node.js 18에서

가지고 오다

JavaScript의 fetch() 메서드는 서버에서 데이터를 요청하는 데 사용됩니다.요청은 JSON 또는 XML로 데이터를 반환하는 모든 유형의 API일 수 있습니다.

노드페치 패키지와 작별하고, Axios요청합니다...이제 fetch API는 기본적으로 글로벌 범위에서 사용할 수 있습니다.

app.get('/', (req, res, next) => {
    // Make a post Request.
    
    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify({
            title: 'foo',
            body: 'bar',
            userId: 1,
        }),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
        },
    })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch(error => {
            console.log(error)
        })

    res.send('Fetch API is available on the global scope by default')
})

우리는 브라우저에서처럼 요청을 할 수 있습니다.

자세한 정보는

슈퍼에이전트(https://github.com/visionmedia/superagent) 의 단순함이 마음에 듭니다.노드와 브라우저 모두에서 동일한 API입니다.

;(async function() {
  var response = await superagent.post('http://127.0.0.1:8125/', {age: 2})
  console.log(response)
})

일치하는 API를 가진 node-message(https://www.npmjs.com/package/node-fetch), 도 있습니다.fetch브라우저에서 - 그러나 수동 쿼리 문자열 인코딩이 필요하거나 내용 유형을 자동으로 처리하지 않거나 다른 작업 슈퍼에이전트가 처리합니다.

약속 기반 HTTP 요청을 찾고 있다면, xios는 그 일을 잘 수행합니다.

  const axios = require('axios');

  axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'})
      .then((response) => console.log(response))
      .catch((error) => console.log(error));

OR

await axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'})

Rest/J SON 요청 게시하기
요청 패키지를 사용하여 Json 변수로 보내야 하는 값을 저장할 수 있습니다.

먼저 npm 설치 요청 --save를 통해 콘솔에 필요한 패키지를 설치합니다.

var request = require('request');

    var options={
                'key':'28',
                'key1':'value',
                'key2':'value'
                }

    request({
             url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?                      
                 minorRev="+options.key+
                 "&cid="+options.key1+
                 "&apiKey="+options.key2,
             method:"POST",
             json:true},function(error,response,body){
                     console.log(body)
               }
    );

은 이은나다니입책결해것의에 대한 나의 입니다.POST그리고.GET.

Post방법:

본문이 JSON 개체인 경우에는 다음을 사용하여 역직렬화하는 것이 중요합니다.JSON.stringify그리고 아마도 설정할 것입니다.Content-Lenght그에 따른 헤더:

      var bodyString=JSON.stringify(body)
      var _headers = {
        'Content-Length': Buffer.byteLength(bodyString)
      };

요청에 쓰기 전에:

request.write( bodyString );

둘 다에 대하여Get그리고.Post메서드:

timeout로 발생할 수 있습니다.socket연결을 해제합니다. 따라서 다음과 같이 처리기를 등록해야 합니다.

request.on('socket', function (socket) {
        socket.setTimeout( self.timeout );
        socket.on('timeout', function() {
            request.abort();
            if(timeout) return timeout( new Error('request timed out') );
        });
    });

그 사이에request핸들러는

       request.on('timeout', function () {
          // Timeout happend. Server received request, but not handled it
          // (i.e. doesn't send any response or it took to long).
          // You don't know what happend.
          // It will emit 'error' message as well (with ECONNRESET code).
          req.abort();
          if(timeout) return timeout( new Error('request timed out') );
        });

저는 두 핸들러를 모두 등록할 것을 강력히 제안합니다.

응답 본문이 청크되므로 청크를 다음에서 콘트해야 합니다.data처리기:

      var body = '';
      response.on('data', function(d) {
          body += d;
      });

에서endbody전체 응답 본문을 포함합니다.

      response.on('end', function() {
        try {
            var jsonResponse=JSON.parse(body);
            if(success) return success( jsonResponse );
        } catch(ex) { // bad json
          if(error) return error(ex.toString());
        }
      });

안전하게 포장할 수 있습니다.try...또 만나theJSON.parse'는 실제로 잘 포맷된 json인지 확신할 수 없고 요청을 할 때 확신할 수 있는 방법이 없기 때문입니다.

모듈:SimpleAPI

/**
 * Simple POST and GET
 * @author Loreto Parisi (loretoparisi at gmail dot com)
*/
(function() {

  var SimpleAPI;

  SimpleAPI = (function() {

    var qs = require('querystring');

    /**
     * API Object model
     * @author Loreto Parisi (loretoparisi at gmail dot com)
     */
    function SimpleAPI(host,port,timeout,ssl,debug,json) {

      this.host=host;
      this.port=port;
      this.timeout=timeout;
      /** true to use ssl - defaults to true */
      this.ssl=ssl || true;
      /** true to console log */
      this.debug=debug;
      /** true to parse response as json - defaults to true */
      this.json= (typeof(json)!='undefined')?json:true;
      this.requestUrl='';
      if(ssl) { // use ssl
          this.http = require('https');
      } else { // go unsafe, debug only please
          this.http = require('http');
      }
    }

    /**
     * HTTP GET
     * @author Loreto Parisi (loretoparisi at gmail dot com)
     */
    SimpleAPI.prototype.Get = function(path, headers, params, success, error, timeout) {

      var self=this;
      if(params) {
        var queryString=qs.stringify(params);
        if( queryString ) {
          path+="?"+queryString;
        }
      }
      var options = {
        headers : headers,
        hostname: this.host,
        path: path,
        method: 'GET'
      };
      if(this.port && this.port!='80') { // port only if ! 80
        options['port']=this.port;
      }
      if(self.debug) {
        console.log( "SimpleAPI.Get", headers, params, options );
      }
      var request=this.http.get(options, function(response) {

          if(self.debug) { // debug
            console.log( JSON.stringify(response.headers) );
          }

          // Continuously update stream with data
          var body = '';
          response.on('data', function(d) {
              body += d;
          });
          response.on('end', function() {
            try {
              if(self.json) {
                var jsonResponse=JSON.parse(body);
                if(success) return success( jsonResponse );
              }
              else {
                if(success) return success( body );
              }
            } catch(ex) { // bad json
              if(error) return error( ex.toString() );
            }
          });
        });
        request.on('socket', function (socket) {
            socket.setTimeout( self.timeout );
            socket.on('timeout', function() {
                request.abort();
                if(timeout) return timeout( new Error('request timed out') );
            });
        });
        request.on('error', function (e) {
          // General error, i.e.
          //  - ECONNRESET - server closed the socket unexpectedly
          //  - ECONNREFUSED - server did not listen
          //  - HPE_INVALID_VERSION
          //  - HPE_INVALID_STATUS
          //  - ... (other HPE_* codes) - server returned garbage
          console.log(e);
          if(error) return error(e);
        });
        request.on('timeout', function () {
          // Timeout happend. Server received request, but not handled it
          // (i.e. doesn't send any response or it took to long).
          // You don't know what happend.
          // It will emit 'error' message as well (with ECONNRESET code).
          req.abort();
          if(timeout) return timeout( new Error('request timed out') );
        });

        self.requestUrl = (this.ssl?'https':'http') + '://' + request._headers['host'] + request.path;
        if(self.debug) {
          console.log("SimpleAPI.Post",self.requestUrl);
        }
        request.end();
    } //RequestGet

    /**
     * HTTP POST
     * @author Loreto Parisi (loretoparisi at gmail dot com)
     */
    SimpleAPI.prototype.Post = function(path, headers, params, body, success, error, timeout) {
      var self=this;

      if(params) {
        var queryString=qs.stringify(params);
        if( queryString ) {
          path+="?"+queryString;
        }
      }
      var bodyString=JSON.stringify(body)
      var _headers = {
        'Content-Length': Buffer.byteLength(bodyString)
      };
      for (var attrname in headers) { _headers[attrname] = headers[attrname]; }

      var options = {
        headers : _headers,
        hostname: this.host,
        path: path,
        method: 'POST',
        qs : qs.stringify(params)
      };
      if(this.port && this.port!='80') { // port only if ! 80
        options['port']=this.port;
      }
      if(self.debug) {
        console.log( "SimpleAPI.Post\n%s\n%s", JSON.stringify(_headers,null,2), JSON.stringify(options,null,2) );
      }
      if(self.debug) {
        console.log("SimpleAPI.Post body\n%s", JSON.stringify(body,null,2) );
      }
      var request=this.http.request(options, function(response) {

          if(self.debug) { // debug
            console.log( JSON.stringify(response.headers) );
          }

          // Continuously update stream with data
          var body = '';
          response.on('data', function(d) {
              body += d;
          });
          response.on('end', function() {
            try {
                console.log("END", body);
                var jsonResponse=JSON.parse(body);
                if(success) return success( jsonResponse );
            } catch(ex) { // bad json
              if(error) return error(ex.toString());
            }
          });

        });

        request.on('socket', function (socket) {
            socket.setTimeout( self.timeout );
            socket.on('timeout', function() {
                request.abort();
                if(timeout) return timeout( new Error('request timed out') );
            });
        });
        request.on('error', function (e) {
          // General error, i.e.
          //  - ECONNRESET - server closed the socket unexpectedly
          //  - ECONNREFUSED - server did not listen
          //  - HPE_INVALID_VERSION
          //  - HPE_INVALID_STATUS
          //  - ... (other HPE_* codes) - server returned garbage
          console.log(e);
          if(error) return error(e);
        });
        request.on('timeout', function () {
          // Timeout happend. Server received request, but not handled it
          // (i.e. doesn't send any response or it took to long).
          // You don't know what happend.
          // It will emit 'error' message as well (with ECONNRESET code).
          req.abort();
          if(timeout) return timeout( new Error('request timed out') );
        });

        self.requestUrl = (this.ssl?'https':'http') + '://' + request._headers['host'] + request.path;
        if(self.debug) {
          console.log("SimpleAPI.Post",self.requestUrl);
        }

        request.write( bodyString );
        request.end();

    } //RequestPost

    return SimpleAPI;

  })();

  module.exports = SimpleAPI

}).call(this);

용도:

// Parameters
// domain: example.com
// ssl:true, port:80
// timeout: 30 secs
// debug: true
// json response:true
var api = new SimpleAPI('posttestserver.com', 80, 1000 * 10, true, true, true); 

var headers = {
    'Content-Type' : 'application/json',
    'Accept' : 'application/json' 
};
var params = {
  "dir" : "post-test"
};
var method = 'post.php';

api.Post(method, headers, params, body
    , function(response) { // success
       console.log( response );
    }
    , function(error) { // error
      console.log( error.toString() );
    }
    , function(error) { // timeout
       console.log( new Error('timeout error') );
    });

이를 달성하는 방법을 설명하는 비디오를 찾았습니다. https://www.youtube.com/watch?v=nuw48-u3Yrg

기본 "http" 모듈을 "querystring" 및 "stringbuilder" 모듈과 함께 사용합니다.응용 프로그램은 웹 페이지에서 두 개의 숫자(두 개의 텍스트 상자 사용)를 가져오고 제출 시 두 숫자의 합계(텍스트 상자의 값 유지)를 반환합니다.이것은 제가 다른 곳에서 찾을 수 있는 가장 좋은 예입니다.

var http = require("http");
var qs = require("querystring");
var StringBuilder = require("stringbuilder");

var port = 9000;

function getCalcHtml(req, resp, data) {
    var sb = new StringBuilder({ newline: "\r\n" });
    sb.appendLine("<html>");
    sb.appendLine(" <body>");
    sb.appendLine("     <form method='post'>");
    sb.appendLine("         <table>");
    sb.appendLine("             <tr>");
    sb.appendLine("                 <td>Enter First No: </td>");

    if (data && data.txtFirstNo) {
        sb.appendLine("                 <td><input type='text' id='txtFirstNo' name='txtFirstNo' value='{0}'/></td>", data.txtFirstNo);
    }
    else {
        sb.appendLine("                 <td><input type='text' id='txtFirstNo' name='txtFirstNo' /></td>");
    }

    sb.appendLine("             </tr>");
    sb.appendLine("             <tr>");
    sb.appendLine("                 <td>Enter Second No: </td>");

    if (data && data.txtSecondNo) {
        sb.appendLine("                 <td><input type='text' id='txtSecondNo' name='txtSecondNo' value='{0}'/></td>", data.txtSecondNo);
    }
    else {
        sb.appendLine("                 <td><input type='text' id='txtSecondNo' name='txtSecondNo' /></td>");
    }

    sb.appendLine("             </tr>");
    sb.appendLine("             <tr>");
    sb.appendLine("                 <td><input type='submit' value='Calculate' /></td>");
    sb.appendLine("             </tr>");

    if (data && data.txtFirstNo && data.txtSecondNo) {
        var sum = parseInt(data.txtFirstNo) + parseInt(data.txtSecondNo);
        sb.appendLine("             <tr>");
        sb.appendLine("                 <td>Sum: {0}</td>", sum);
        sb.appendLine("             </tr>");
    }

    sb.appendLine("         </table>");
    sb.appendLine("     </form>")
    sb.appendLine(" </body>");
    sb.appendLine("</html>");
    sb.build(function (err, result) {
        resp.write(result);
        resp.end();
    });
}

function getCalcForm(req, resp, data) {
    resp.writeHead(200, { "Content-Type": "text/html" });
    getCalcHtml(req, resp, data);
}

function getHome(req, resp) {
    resp.writeHead(200, { "Content-Type": "text/html" });
    resp.write("<html><html><head><title>Home</title></head><body>Want to some calculation? Click <a href='/calc'>here</a></body></html>");
    resp.end();
}

function get404(req, resp) {
    resp.writeHead(404, "Resource Not Found", { "Content-Type": "text/html" });
    resp.write("<html><html><head><title>404</title></head><body>404: Resource not found. Go to <a href='/'>Home</a></body></html>");
    resp.end();
}

function get405(req, resp) {
    resp.writeHead(405, "Method not supported", { "Content-Type": "text/html" });
    resp.write("<html><html><head><title>405</title></head><body>405: Method not supported</body></html>");
    resp.end();
}

http.createServer(function (req, resp) {
    switch (req.method) {
        case "GET":
            if (req.url === "/") {
                getHome(req, resp);
            }
            else if (req.url === "/calc") {
                getCalcForm(req, resp);
            }
            else {
                get404(req, resp);
            }
            break;
        case "POST":
            if (req.url === "/calc") {
                var reqBody = '';
                req.on('data', function (data) {
                    reqBody += data;
                    if (reqBody.length > 1e7) { //10MB
                        resp.writeHead(413, 'Request Entity Too Large', { 'Content-Type': 'text/html' });
                        resp.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
                    }
                });
                req.on('end', function () {
                    var formData = qs.parse(reqBody);
                    getCalcForm(req, resp, formData);
                });
            }
            else {
                get404(req, resp);
            }
            break;
        default:
            get405(req, resp);
            break;
    }
}).listen(port);

게시물을 처리하고 프로젝트 요청을 받기 위해 낮은 수준의 유틸리티를 만드는 동안 많은 어려움을 겪은 후, 저는 여기에 제 노력을 게시하기로 결정했습니다.JSON 데이터 전송을 위해 http 및 https POST 요청을 수행하기 위한 스니펫이 수락된 답변의 대부분을 차지합니다.

const http = require("http")
const https = require("https")

// Request handler function
let postJSON = (options, postData, callback) => {

    // Serializing JSON
    post_data = JSON.stringify(postData)

    let port = options.port == 443 ? https : http

    // Callback function for the request
    let req = port.request(options, (res) => {
        let output = ''
        res.setEncoding('utf8')

        // Listener to receive data
        res.on('data', (chunk) => {
            output += chunk
        });

        // Listener for intializing callback after receiving complete response
        res.on('end', () => {
            let obj = JSON.parse(output)
            callback(res.statusCode, obj)
        });
    });

   // Handle any errors occurred while making request
    req.on('error', (err) => {
        //res.send('error: ' + err.message)
    });

    // Request is made here, with data as string or buffer
    req.write(post_data)
    // Ending the request
    req.end()
};

let callPost = () => {

    let data = {
        'name': 'Jon',
        'message': 'hello, world'
    }

    let options = {
        host: 'domain.name',       // Your domain name
        port: 443,                 // 443 for https and 80 for http
        path: '/path/to/resource', // Path for the request
        method: 'POST',            
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(data)
        }
    }

    postJSON(options, data, (statusCode, result) => {
        // Handle response
        // Process the received data
    });

}

Axios는 브라우저 및 Node.js에 대한 약속 기반 HTTP 클라이언트입니다.Axios를 사용하면 REST 끝점에 비동기 HTTP 요청을 쉽게 보내고 CRUD 작업을 수행할 수 있습니다.일반 JavaScript 또는 Vue 또는 React와 같은 라이브러리에서 사용할 수 있습니다.

const axios = require('axios');

        var dataToPost = {
          email: "your email",
          password: "your password"
        };

        let axiosConfiguration = {
          headers: {
              'Content-Type': 'application/json;charset=UTF-8',
              "Access-Control-Allow-Origin": "*",
          }
        };

        axios.post('endpoint or url', dataToPost, axiosConfiguration)
        .then((res) => {
          console.log("Response: ", res);
        })
        .catch((err) => {
          console.log("error: ", err);
        })
let request = require('request');
let jsonObj = {};
request({
    url: "https://myapii.com/sendJsonData",
    method: "POST",
    json: true,
    body: jsonObj
    }, function (error, resp, body){
       console.log(resp);
});

또는 이 라이브러리를 사용할 수 있습니다.

let axios = require("axios");
let jsonObj = {};

const myJsonAPI = axios.create({
   baseURL: 'https://myapii.com',
   timeout: 120*1000
});

let response = await myJsonAPI.post("sendJsonData",jsonobj).catch(e=>{
    res.json(e);
});
console.log(response);

추가 구성 옵션 및 사용자 지정 헤더를 사용하는 axios.post 요청의 다른 공리 예제를 게시합니다.

var postData = {
  email: "test@test.com",
  password: "password"
};

let axiosConfig = {
  headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "Access-Control-Allow-Origin": "*",
  }
};

axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
  console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
  console.log("AXIOS ERROR: ", err);
})

원하는 경우 Node.js를 사용하여 임의 HTTP 요청을 만들 수 있습니다.http라이브러리 - 새 기능을 제공하지 않는 타사 패키지를 사용할 필요가 없습니다.

원하는 경우 아래 예제와 같이 Node.js 기본 제공 기능을 사용할 수 있습니다.

https://nodejs.org/api/http.html#httprequesturl-options-callback

다음에 대한 설명서의 예제http.request에서는 "hello world" POST 요청을 수행하는 방법을 보여 줍니다.

여기 그 예가 있습니다.Node.js를 배우고 더 많은 리소스를 원하는 경우와 같이 의견에 질문합니다.

const http = require('node:http');

const postData = JSON.stringify({
    'msg': 'Hello World!',
});

const options = { 
    hostname: 'www.google.com',
    port: 80, 
    path: '/upload',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData),
    },  
};

const req = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    }); 
    res.on('end', () => {
        console.log('No more data in response.');
    }); 
});

req.on('error', (e) => {
    console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();
~                                                                                                   
~                                                                                                   
~                                 

요청 종속성을 사용합니다.

간단한 솔루션:

 import request from 'request'
 var data = {
        "host":"127.1.1.1",
        "port":9008
    }

request.post( baseUrl + '/peers/connect',
        {
            json: data,  // your payload data placed here
            headers: {
                'X-Api-Key': 'dajzmj6gfuzmbfnhamsbuxivc', // if authentication needed
                'Content-Type': 'application/json' 
            }
        }, function (error, response, body) {
            if (error) {
                callback(error, null)
            } else {
                callback(error, response.body)
            }
        });

Request-Promise약기반 . 응답 2xx 이외의 http 응답 코드로 인해 약속이 거부됩니다. 수 . = false 션 하 쓸 니 있 false sys 다 습 = false

var options = {
  method: 'POST',
  uri: 'http://api.posttestserver.com/post',
  body: {
  some: 'payload'
 },
  json: true // Automatically stringifies the body to JSON
};

rp(options)
.then(function (parsedBody) {
    // POST succeeded...
})
.catch(function (err) {
    // POST failed...
});

XML 요청이 필요할 경우 xios 라이브러리와 코드를 공유하겠습니다.

const {default: axios} = require('axios');

let xmlString = '<XML>...</XML>';

axios.post('yourURL', xmlString)
 .then((res) => {
   console.log("Status: ", res.status);
   console.log("Body: ", res.data);
 })
 .catch((err) => {
   console.error("Error: ", err);
 });

언급URL : https://stackoverflow.com/questions/6158933/how-is-an-http-post-request-made-in-node-js

반응형