Node.js හි HTTP POST ඉල්ලීමක් කරන්නේ කෙසේද?


966

Node.js හි දත්ත සමඟ පිටතට යන HTTP POST ඉල්ලීමක් කරන්නේ කෙසේද?


16
ජෙඩ් වොට්සන්ගේ පිළිතුරෙහි යෝජනා කර ඇති පරිදි , ඔබ පහත් මට්ටමේ API එකක් ලියන්නේ නැත්නම් ඉල්ලීම භාවිතා කිරීමට මම තරයේ නිර්දේශ කරමි .
namuol

5
ඔබ භාවිතා කළ හැකි node-fetchදේශීය ක ක්රියාත්මක වන fetchHTTP ඉල්ලීම් වලට JavaScript ක්රමය.
Fez Vrasta

මෙම පෝස්ට් ඉල්ලීම භාවිතා කිරීම සඳහා මූලික භාවිත අවස්ථා ආවරණය කරයි. blog.modulus.io/node.js-tutorial-how-to-use-request-module
Shaswat Rungta


2
ඉල්ලීම මොඩියුලය වේ ඉහත අදහස් නිර්දේශ නොසලකා හරිනු දැන්
electrovir

Answers:


870

ගූගල් කම්පයිලර් ඒපීඅයි වෙත පෝස්ට් ඉල්ලීමක් කිරීමට node.js භාවිතා කිරීම පිළිබඳ උදාහරණයක් මෙන්න:

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

දෘ c කේත කරන ලද නූල වෙනුවට ගොනුවකින් දත්ත පළ කරන්නේ කෙසේදැයි පෙන්වීමට මම කේතය යාවත්කාලීන කර ඇත. මෙය fs.readFileසාක්ෂාත් කර ගැනීම සඳහා එය අසින්ක් විධානය භාවිතා කරයි, සාර්ථක කියවීමකින් පසු සත්‍ය කේතය පළ කරයි. දෝෂයක් තිබේ නම්, එය විසි කරනු ලැබේ, දත්ත නොමැති නම් ක්‍රියාවලිය අසාර්ථක බව දැක්වීමට negative ණ අගයක් සමඟ පිටවෙයි.


4
අන්තර්ගත දිග ශීර්ෂය නිවැරදිව ගණනය කර තිබේද? බයිට් යැයි සිතමු, නේද?
එරික්

7
querystring.stringify() කැදැලි සහිත වස්තූන් සඳහා සහය නොදක්වන බව සලකන්න , එබැවින් ඔබට qs.stringify()ඒ වෙනුවට භාවිතා කිරීමට අවශ්‍ය විය හැකිය .
johndodo

52
Content-Lengthබයිට් වන අතර එය අනිවාර්යයෙන්ම නූල් දිග (UTF-16 යනාදිය) නොවේ. භාවිතා කිරීම Buffer.byteLength(data)සැමවිටම නිවැරදි වනු ඇත.
greenimpala

4
සම්මත තැපැල් querystring.stringifyදත්ත යැවීම සඳහා, ඇති වස්තුව ඔබේම දත්ත වස්තුවක් විය යුතුය, මෙම පිළිතුරෙහි පෙන්වන කුණු නොවේ (ගොනු පදනම් කරගත් වස්තු සඳහා එය ප්‍රයෝජනවත් විය හැකිද?). මම අවුරුදු ගණනාවක් තිස්සේ එහි සිරවී සිටියෙමි ... stackoverflow.com/questions/9768192/… මගේ සම්පූර්ණ විසඳුම ලබා දුන්නේය
RozzA

7
ගොට්චා: ඔබ එස්එස්එල්-සංකේතාත්මක වෙබ් අඩවියක් භාවිතා කරන්නේ නම්, ඔබට "https" පුස්තකාලය අවශ්‍ය වේ. ඔබට වරාය 443 දක්වා වෙනස් කළ නොහැක.
ඩේව් කොලින්ස්

1150

ඔබ ඉල්ලීම් පුස්තකාලය භාවිතා කරන්නේ නම් මෙය බෙහෙවින් පහසු වේ.

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 ඉල්ලීම් පහසු කරයි, අත්සන් අත්සන් කිරීම (ට්විටර් යනාදිය සඳහා), බහු-කොටස් ආකෘති (උදා: ගොනු උඩුගත කිරීම සඳහා) සහ ප්‍රවාහය කළ හැකිය.

ඉල්ලීම ස්ථාපනය කිරීම සඳහා විධානය භාවිතා කරන්න npm install request


155
{form: {key: 'value'}} වෙනුවට {json: {key: 'value'} by ආදේශ කළ යුතුය (ප්‍රශ්නය ආකෘති වලට විශේෂිත නොවන බැවින්). යමෙක් 'පෝරමය' සහ 'ජේසන්' යනු ඉල්ලීම් පුස්තකාල මූල පද මිස අභිරුචි දත්තවල කොටසක් නොවන බව තේරුම් ගත යුතුය (මෙම අන්තිම අදහස් දැක්වීමට තරම් සුළු දෙයක් බැවින් එය හඳුනා ගැනීමට මට යම් කාලයක් ගත විය ...)
බ්ලෙසෙල්

7
මම දිගටම මෙම ප්‍රශ්නයට පිළිතුරු දෙමි. එය සැබවින්ම ප්‍රශ්නයට පිළිතුර විය යුතුය.
ස්පෙන්සර් කෝර්මොස්

6
මෙම පිළිතුර සඳහා ඔබ රන් ලාංඡනයක් ලැබීමට සුදුසුයි. එය පිළිගත් එකට වඩා බෙහෙවින් ප්‍රයෝජනවත් වේ ... එය දැනටමත් 2012 දී පැවතුනි? වාව්
සොල්ටන් ෂ්මිට්

3
'npm install --save request' විධානය ක්‍රියාත්මක කිරීමෙන් ඔබට යැපීම එකතු කිරීමට අවශ්‍ය විය හැකිය
ෂැඩි ෂෙරිෆ්

32
මෙම පුස්තකාලය අතහැර දමා ඇත.
එවර්ලර්

136

ඔබට ඉල්ලීම් පුස්තකාලය භාවිතා කළ හැකිය. 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);
});

ඔවුන්ගේ ලියකියවිලි සමාලෝචනය කිරීමෙන් පසුව. එය පහත සඳහන් දේ සඳහන් කරයි: json - ශරීරය සකසන නමුත් JSON අගය නිරූපණය කරන අතර අන්තර්ගත වර්ගය එකතු කරයි: යෙදුම / json ශීර්ෂය. ඊට අමතරව, ප්‍රතිචාර ශරීරය JSON ලෙස විග්‍රහ කරයි. ඒ කියන්නේ json = true නම්, එය ශීර්ෂය සහ json සහ ශරීරය සකසනු ඇත. එසේ නොමැතිනම්, ශීර්ෂක කට්ටලයක් නොමැති අතර පෙළ ලෙස විග්‍රහ කරන්න. (ඉහත XML උදාහරණය මෙන්). එමඟින් ඉල්ලීම API පහසු සහ සරල නමුත් පළමු වරට තේරුම් ගැනීමට අපහසු වේ.
ජොෂියා චෝයි

එය තාක්‍ෂණිකව ඔවුන්ගේ ලේඛනයේ ඇත, නමුත් උදාහරණ කිසිවක් එය නොපෙන්වයි - දත්ත පමණක් සාදයි. එය පිදුරු මඩුවේ ඉඳිකටුවක් වන අතර, ඒ නිසා එය විශාල අතපසු වීමකි, මන්දයත් මම ජේඑස් හි අජැක්ස් භාවිතා කරන දෙවන නිරන්තර ක්‍රමය මෙය වන අතර එය වෙබයේ වඩාත් සුලභ එකක් වේ.
කයිල් බේකර්

Request.post භාවිතා කිරීම POST ක්‍රමය ලෙස සඳහන් කිරීමට වඩා IMO තරමක් හොඳයි.
Request.post

16
මෙම පුස්තකාලය අතහැර දමා ඇත.
එවර්ලර්

44

නිෂ්පාදන කටයුතු සඳහා මම රෙස්ලර් සහ ඉඳිකටු භාවිතා කරමි . ඔවුන් දෙදෙනාම ස්වදේශීය httprequest ට වඩා බලවත් ය. මූලික සත්‍යාපනය, විශේෂ ශීර්ෂ ඇතුළත් කිරීම හෝ ගොනු උඩුගත කිරීම / බාගැනීම සමඟ ඉල්ලීමට හැකිය.

පශ්චාත් / ලබා ගැනීමේ ක්‍රියාකාරිත්වය සම්බන්ධයෙන් ගත් කල, ඒවා httpsquest භාවිතා කරන අමු අජැක්ස් ඇමතුම් වලට වඩා භාවිතා කිරීමට වඩා සරල ය.

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

මම ඉඳිකටුවට පෙර ඉල්ලීම, නෝඩ්-ෆෝම්-ඩේටා සහ සුපර්ජන්ට් උත්සාහ කළෙමි. බහුකාර්ය පෝරම ගොනු උඩුගත කිරීමට උත්සාහ කරන විට මට නිවැරදිව වැඩ කළ එකම එක ඉඳිකටුවක් පමණි.
පෝල් යන්ග්

40

සරල හා යැපීම් රහිත. ඔබට ප්‍රති .ලයක් බලාපොරොත්තුවෙන් සිටීමට පොරොන්දුවක් භාවිතා කරයි. එය ප්‍රතිචාර ශරීරය නැවත ලබා දෙන අතර ප්‍රතිචාර තත්ව කේතය පරීක්ෂා නොකරයි.

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 body = Buffer.concat(chunks);
                switch(res.headers['content-type']) {
                    case 'application/json':
                        body = JSON.parse(body);
                        break;
                }
                resolve(body)
            })
        })
        req.on('error',reject);
        if(body) {
            req.write(body);
        }
        req.end();
    })
}

භාවිතය:

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',
    })
})

කුමක්ද writeමත ක්රමය req,write()සඳහා භාවිතා කරනු ඇත?
අරි

1
Ri ඒ ඉල්ලීමේ සිරුර ලියයි ... nodejs.org/api/…
mpen

ස්තූතියි, මෙය ඇත්තෙන්ම අව් ලැම්බා සඳහා සුදුසු ය. දැන් එය සමඟ වැඩ කිරීමට අසින්ක් අවශ්‍ය වේ.
Tuananhcwrs

25

නෝඩ් හි HTTP POST ඉල්ලීමක් කිරීමට ඔබට භාවිතා කළ හැකි විවෘත කේත පුස්තකාල දුසිම් ගණනක් ඇත.

1. ඇක්සියෝස් (නිර්දේශිත)

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

2. ඉඳිකටුවක්

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

3. ඉල්ලීම

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

4. ස්වදේශීය 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();

විස්තර සඳහා, මෙම ලිපිය බලන්න .


21

ඔබට nodeJS + සඳහා ලියූ ඇත්තෙන්ම සිසිල් හා සරල HTTP සේවාදායකයක් වන Requestify භාවිතා කළ හැකිය .

පහත සඳහන් දේ කරන්න:

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

1
එය මට වැඩ කරන්නේ නැත, මෙහි ගැටලුව බලන්න: github.com/ranm8/requestify/issues/2
Erel Segal-Halevi

20

යාවත්කාලීන කිරීම 2020:

මම සැබවින්ම ෆින් භුක්ති වින්දා - අතිශය සැහැල්ලු Node.js HTTP සේවාදායකයා

එය වෙනස් ආකාර දෙකකින් භාවිතා කළ හැකිය. එකක් පොරොන්දු (අසින්ක් / බලා සිටින්න) සහ අනෙක සාම්ප්‍රදායික ඇමතුම් ආපසු ගැනීමේ ශෛලීන් සමඟ ය.

හරහා ස්ථාපනය කරන්න: 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

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.

යුනිරෙස්ට් විසින් ඉල්ලීම් වස්තුවට කෙලින්ම ප්‍රවේශ වීමේ ක්‍රම සපයයි.

උදාහරණයක්:

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

1
ඉතා හොඳ පෙනුමක් ඇති බව මට පෙනී ගිය තවත් එකක් නම් github.com/request/request එය අවම වශයෙන් මෙම ලිවීමට වඩා ඒකාකාරී නොවන තරමට වඩා ජනප්‍රිය බව පෙනේ
Lochlan

ඉල්ලීමට මට සහතික කළ හැකිය. එය ඉතා හොඳ පුස්තකාලයකි. ඉල්ලීම වඩා පහත් මට්ටමේ ක්‍රියාකාරිත්වයක් සපයන බව මට පෙනී ගොස් ඇති බැවින් එය විශේෂිත යෙදුම් සඳහා භාවිතා කිරීම සුදුසුය. මම අනිවාර්යයෙන්ම පහත් මට්ටමේ දේවල් ගැන තැකීමක් නොකරන විට, යුනිරෙස්ට් ප්‍රමාණවත් බව මට පෙනේ.
ලෙවි රොබට්ස්

ඉල්ලීම මත රඳා පවතින විට unirest සැහැල්ලු බරක් ලෙස සලකන්නේ ඇයි? ඉල්ලීම මත යැපීම් 22 ක් ඇත, මෙය සැහැල්ලු වන්නේ කෙසේදැයි මම නොදනිමි
raphadko

@raphadko මට විශ්වාසයි වසර ගණනාවක් තිස්සේ විශේෂාංග පිපිරීමක් සිදුවී ඇති බව. මම මගේ පිළිතුර පළ කළ වේලාව පරීක්ෂා කිරීමට වග බලා ගන්න;)
ලෙවි රොබට්ස්

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

ඉල්ලීම හෝ ප්‍රතිචාරය මත ඉල්ලීම් පෝස්ට් බොඩි බැලීමට ක්‍රමයක් තිබේද?
jacoballenwood

14

ඉල්ලීම කිරීමට මා භාවිතා කරන සරලම ක්‍රමය මෙයයි: 'ඉල්ලීම' මොඩියුලය භාවිතා කිරීම.

'ඉල්ලීම' මොඩියුලය ස්ථාපනය කිරීමට විධානය:

$ 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' මොඩියුලය භාවිතා කළ හැකිය.


2
මෙම පුස්තකාලය අතහැර දමා ඇත.
යූරි ටකචෙන්කෝ

12

සුපර්ජන්ට් ( 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-fetch ( https://www.npmjs.com/package/node-fetch ) ද ඇත fetch- කෙසේ වෙතත් මේ සඳහා අතින් විමසුම් වචන කේතීකරණයක් අවශ්‍ය වේ, අන්තර්ගත වර්ග ස්වයංක්‍රීයව හසුරුවන්නේ නැත, නැතහොත් ඒ නිසා වෙනත් ඕනෑම වැඩක් අධිපති විසින් කරයි.


1
ඉඳිකටුවක්, යුනිරස්ට් සහ සමට වඩා වෙනස්ව, එය සැහැල්ලු බරින් යුක්ත වේ (සුපිරි: 16k, unirest: 1M, ඉඳිකටු: 530K)
Lars

9

ඔබ පොරොන්දු පදනම් කරගත් HTTP ඉල්ලීම් සොයන්නේ නම්, අක්ෂය සිය කාර්යය මනාව ඉටු කරයි.

  const axios = require('axios');

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

හෝ

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

6

විවේක / JSON ඉල්ලීම පළ කිරීම සඳහා
අපට ඉල්ලීම් පැකේජය භාවිතා කර Json විචල්‍යයෙන් යැවිය යුතු අගයන් සුරැකිය හැකිය.

පළමුවෙන්ම අවශ්‍ය පැකේජය ඔබේ කොන්සෝලය තුළ ස්ථාපනය කරන්න npm install request --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)
               }
    );

2
කිසි විටෙකත් ඔබේම විමසුම් නූලක් සාදන්න එපා. ඔබේ අගයන් නිසි ලෙස කේතනය කිරීමට ඔබ නොසලකා හැර ඇත. මේ සඳහා Node.js සතුව පුස්තකාලයක් ඇත: nodejs.org/api/querystring.html
බ්‍රැඩ්

මෙම පුස්තකාලය අතහැර දමා ඇත.
යූරි ටකචෙන්කෝ

4

මෙය සාක්ෂාත් කර ගන්නේ කෙසේද යන්න පැහැදිලි කරන වීඩියෝවක් මට හමු විය: https://www.youtube.com/watch?v=nuw48-u3Yrg

එය "විමසුම්" සහ "ස්ට්‍රිංබිල්ඩර්" මොඩියුල සමඟ සුපුරුදු "http" මොඩියුලය භාවිතා කරයි. යෙදුම වෙබ් පිටුවකින් අංක දෙකක් (පෙළ කොටු දෙකක් භාවිතා කරමින්) ගෙන ඉදිරිපත් කළ විට, එම දෙකේ එකතුව (පෙළ කොටු වල අගයන් දිගටම පවත්වා ගෙන යයි). මට වෙනත් ඕනෑම තැනක සොයාගත හැකි හොඳම උදාහරණය මෙයයි.

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

4

මෙය 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;
      });

දී endඇති bodyමුළු ප්රතිචාර ශරීරය අඩංගු වනු ඇත:

      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... උඩ theඔබ එය ඇත්තටම මනා-ආකෘතියකින් සුසැදි json වන අතර, ඔබ ඉල්ලීම කරන්න අවස්ථාවේ වග බලා ගන්න විය කිරීමට කිසිදු ක්රමයක් නොමැති බව තහවුරු විය නොහැකි නිසා JSON.parse`.

මොඩියුලය: 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') );
    });

4

තනතුර හැසිරවීමට සහ මගේ ව්‍යාපෘතිය සඳහා ඉල්ලීම් ලබා ගැනීමට පහත් මට්ටමේ උපයෝගීතාවයක් නිර්මාණය කරමින් බොහෝ වෙහෙස මහන්සි වී, මගේ උත්සාහය මෙහි පළ කිරීමට මම තීරණය කළෙමි. පිළිගත් පිළිතුරට අනුව, 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
    });

}

2
ඔබ කිසි විටෙකත් අනුක්‍රමික පෝස්ට් ඩේටා භාවිතා නොකරන්නේද? js වස්තුව ලෙස ලිවීම පෙරනිමියෙන් බෆරයට පරිවර්තනය වේද?
ThatBrianDude

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

requestපුස්තකාලය අතහැර දමා ඇත.
යූරි ටකචෙන්කෝ

3

ඇක්සියෝස් යනු බ්‍රව්සරය සහ Node.js සඳහා පොරොන්දු මත පදනම් වූ HTTP සේවාදායකයෙකි. REST අන්ත ලක්ෂ්‍යවලට අසමමුහුර්ත HTTP ඉල්ලීම් යැවීම සහ CRUD මෙහෙයුම් සිදු කිරීම ඇක්සියෝස් පහසු කරයි. එය සරල ජාවාස්ක්‍රිප්ට් හෝ 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);
        })

2

අතිරේක වින්‍යාස විකල්ප සහ අභිරුචි ශීර්ෂ භාවිතා කරන 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);
})


0

ඉල්ලීම් පරායත්තතාවය භාවිතා කිරීමෙන් .

සරල විසඳුම:

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

3
කොහෙන්ද request?
කෝඩි බග්ස්ටයින්

මෙම පුස්තකාලය අතහැර දමා ඇත.
යූරි ටකචෙන්කෝ

0

Request-Promiseපොරොන්දු පදනම් කරගත් ප්‍රතිචාරයක් සපයයි. 2xx හැර http ප්‍රතිචාර කේත පොරොන්දුව ප්‍රතික්ෂේප කිරීමට හේතු වේ. විකල්ප සැකසීමෙන් මෙය නැවත ලිවිය හැකිය. Simple = 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...
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.