B
B
Bekkazy2018-04-10 11:44:28
Node.js
Bekkazy, 2018-04-10 11:44:28

How to send a cURL request in Node js?

I'm using the curl-request library .
There is a request:
curl -D- -u fred:fred -X POST --data {see below} -H "Content-Type: application/json" localhost:8090/rest/api/2/issue
With the following data:
{
" fields":
{
"project":
{
"key": "TEST"
},
"parent":
{
"key": "TEST-101"
},
"summary": "Sub-task of TEST-101",
"description ": "Don't forget to do this too.",
"issuetype":
}.
The question is where to insert -u (authorization) in this library? I can't figure out cURL at all.
Where do you put the rest of the data?
There are many questions and no answers in the documentation. First time with cURL

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aves, 2018-04-10
@Bekkazy

It could be something like this:

const Curl = require('curl-request');

const req = new Curl();
const {auth: {BASIC}, option: {HTTPAUTH, USERNAME, PASSWORD}} = req.libcurl;

const url = 'localhost:8090/rest/api/2/issue';
const user = 'fred';
const password = 'fred';
const headers = ['Content-Type: application/json'];
const data = `{
  "fields": {
    "project": {
      "key": "TEST"
    },
    "parent": {
      "key": "TEST-101"
    },
    "summary": "Sub-task of TEST-101",
    "description": "Don't forget to do this too.",
    "issuetype": {
      "id": "5"
    }
  }
}`;

req
  .setOpt(HTTPAUTH, BASIC)
  .setOpt(USERNAME, user)
  .setOpt(PASSWORD, password)
  .setHeaders(headers)
  .setBody(data)
  .post(url)
  .then(res => { console.log(res) })
  .catch(e => { console.error(e) });

A
Abigovor, 2018-04-10
@Abigovor

In your case, it will look something like this
. Unfortunately, I'm not familiar with curl-request, I'm not sure if a regular object can be sent

const curl = new (require( 'curl-request' ))();

curl
.setHeaders([
    'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=', // dXNlcm5hbWU6cGFzc3dvcmQ= - это username:password в base64 кодировке 
    'Content-Type: application/json'
])
.setBody(dataObject)  // объект с передаваемыми данными
.post('https://localhost:8090/rest/api/2/issue')
.then(({statusCode, body, headers}) => {
    console.log(statusCode, body, headers)
})
.catch((e) => {
    console.log(e);
});

example using request-promise 100% will work
const rp = require('request-promise');

var options = { 
  method: "POST", 
  uri: "https://localhost:8090/rest/api/2/issue", 
  body: dataObject, // объект с данными для сервера
  headers:{"Authorization":"Basic dXNlcm5hbWU6cGFzc3dvcmQ="}, // dXNlcm5hbWU6cGFzc3dvcmQ= - это username:password в base64 кодировке
  json: true
}

rp(options)
  .then(data => {
    console.log( JSON.parse(data) );
  })
  .catch(err => console.log('error ', err))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question