0

How to post Json data via node js either with form-data or via request ?

Using form-data. It does not allow to send custom headers and if replaced bodyParams.getHeaders() with custom headers it does not send request data https://www.npmjs.com/package/form-data

        const smsResponse = await request.post(url, bodyParams, {headers:bodyParams.getHeaders()})

Using Request it does not allow to send parameters require('request');

  const subscription = await request.post(url, body, {headers:{'Accept':'text/html'}})

Postman curl request It works via postman. tried to use postman nodejs request code but it fails

curl --location --request POST 'https://personalsite.com//test.php' \
--header 'accept: text/html' \
--header 'SECRET-TOKEN-MESSAGE: dataforport' \
--header 'Content-Type: application/json' \
--header 'Cookie: PHPSESSID=1d2shuebo7lal8sn2itgppvfk4' \
--data-raw '{
  "mobileno": "888888888",
  "messagetext": "Test message"
}'

Tried but it did not worked Node.js: How to send headers with form data using request module?

insoftservice
  • 820
  • 8
  • 15
  • What is the error you are receiving? Where is the request var coming from ? – Florian Sep 01 '21 at 15:21
  • @Florian there is no error . If you are using form-data it either sends request parameters or it sends custom headers. In request it only sends headers but no parameters. – insoftservice Sep 01 '21 at 15:57
  • @jfriend00 How to post Json data via node js either with form-data or via request ? have provided the link of the library in question – insoftservice Sep 01 '21 at 15:58

1 Answers1

0

Use new Headers() to build your header.

https://developer.mozilla.org/en-US/docs/Web/API/Request/Request


var myHeaders = new Headers();
myHeaders.append('Accept', 'text/html');

var myInit = { method: 'POST',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default',
               body: JSON.stringify({coffee: 'yes...'})
 };

var myRequest = new Request('https://personalsite.com//test.php',myInit);

fetch(myRequest).then(function(response) {
  console.log(response)
});
Florian
  • 725
  • 6
  • 27
  • How to pass parameters in your code . Have you tested ? I am able to send either parameters or headers but i want to pass both parameters and headers – insoftservice Sep 01 '21 at 16:00
  • You can `JSON.stringify` your content. You can also have a look at the native `new FormData` . – Florian Sep 01 '21 at 17:32
  • May i know how many different libraries i have to install , 1 > Header 2> Request and 3> fetch . Request = request right ? – insoftservice Sep 01 '21 at 18:31
  • Well you do not install them. They are native Javascript libraries. But I would recommend to install and use Axios for making requests. – Florian Sep 01 '21 at 18:54