Home node.js How to send POST Request with Nodejs

How to send POST Request with Nodejs

Author

Date

Category

How to send a MultiPart / Form-Data query via the POST method from the Nodejs server via the HTTP Library || https?

I can not understand where to put the body of the request, it seems to be stored in the headlines but I can not find in the Node JS and Developer Mozilla documentation.

I suggested how to make get requests, but with Post there are small difficulties.


Answer 1, Authority 100%

You can so

const https = require ('https')
Const Data = JSON.Stringify ({
 TODO: 'BUY THE MILK'
})
Const Options = {
 HostName: 'flaviocopes.com',
 Port: 443,
 Path: '/ Todos',
 Method: 'POST',
 Headers: {
  'Content-Type': 'Application / Json',
  'Content-Length': Data.Length
 }
}
Const Req = Https.Request (Options, (Res) = & gt; {
 Console.log (`Statuscode: $ {res.statuscode}`)
 Res.ON ('Data', (D) = & GT; {
  Process.stdout.Write (D)
 })
})
REQ.ON ('Error', (Error) = & gt; {
 Console.error (Error)
})
REQ.WRITE (DATA)
REQ.End ()

If a multipart then you can so

var fs = require ('fs');
var Request = Require ('Request');
Request.post ({
  URL: 'https://slack.com/api/files.upload',
  FormData: {
    File: fs.createReadStream ('sample.zip'),
    Token: '### Access Token ###',
    FileType: 'Zip',
    FileName: 'samplefilename',
    Channels: 'sample',
    title: 'sampletle',
  },
}, FUNCTION (ERROR, RESPONSE, BODY) {
  Console.log (Body);
});

or other example Hence

import * as formata from 'form-data';
Import {Request} from 'http';
Import {CreateReadStream} from 'Fs';
Const ReadStream = CreateReadStream ('./ photo.jpg');
Const Form = New FormData ();
Form.append ('Photo', ReadStream);
Form.append ('firstName', 'marcin');
Form.append ('LastName', 'Wanago');
Const Req = Request (
 {
  Host: 'LocalHost',
  port: '5000',
  Path: '/ Upload',
  Method: 'POST',
  Headers: Form.getHeaders (),
 },
 Response = & gt; {
  Console.log (response.statuscode); // 200.
 }
);
form.pipe (REQ);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions