Struggling with NodeJs POST request issue

Let's imagine I have a specific URL

https://exampleAPI.com/authorize?param1=value1&param2=value2

Where param1 and param2 are the payload values being sent. How can I execute a POST request in this particular way?

I attempted the following:

var https = require('https')

var options = {
    url: 'https://exampleAPI.com/authorize?param1=value1&param2=value2',
    method: 'POST',
    headers: {
         ....
    }
}

https.request(options, function(res) {
    var str = ""
    res.on('data', function(data){
        str+=data
    })
    res.on('end', function() {
        console.log(str)
    })
})

I'm not receiving any data back. What could I be doing incorrectly?

Edit: Here is the structure I believe is correct:

REQUEST
POST https://exampleAPI.com/us/oauth/v2/authorize?response_type=code&client_id=exampleId&redirect_uri=exampleSite.com HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.2.3.0
Content-Type: application/x-www-form-urlencoded
Host: exampleAPI.com
Content-Length: 98
Accept-Encoding: gzip, deflate

username=someuser&password=somepassword&action=Log%20In&sessionID=someSessionId

Answer №1

Transformed:

https.request(options, function(res) {
    var str = "";
    res.on('data', function(data){
        str+=data;
    });
    res.on('end', function() {
        console.log(str);
    });
});

Into this:

var apiCall = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

apiCall.on("error", (e) => {console.error(e)});
apiCall.end();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue's V-IF directive to compare dates

On my website, I have an object that contains a field named available_at with the date in the format of 2019-08-08 I have a working HTML table utilizing Vue bindings but I am unsure how to compare the timestamp above using the built-in Date.now() method ...

Having trouble with create-react-app? Seeking assistance from the community! Your help would be greatly

Recently attempted to build my first React app, but it seems like React is not in the mood to greet me. After installing Node.js and create-react-app, double-checking their versions to ensure proper installation, I proceeded to create the React app using t ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...

Using Vue.js to detect changes in a value and dynamically highlight the text

I am working on a simple script that generates random numbers every few moments. I want to change the background color whenever the random number is not equal to the one before it. Is this possible? For example, if the random numbers generated are 1, 1, an ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

If I do not specify whether a variable is declared using var or let, what will be its scope?

As someone who is new to JavaScript, please forgive me if my question is not entirely valid. What will be the scope and type (var/let) of a variable if I do not specifically define it as var or let? For example: function f1(){ a="Sample" console.log(" ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

Is there a way to make this eval() function function properly in Internet Explorer?

My JavaScript code is fetching another JavaScript "class" from a different XHTML page. The fetched JavaScript looks like this: (function() { this.init = function() { jQuery("#__BALLOONS__tabs").tabs(); }; }) Once the f ...

Could a commenting feature be seamlessly integrated directly into the video player, accessible with a simple click?

I'm exploring the idea of developing a video player that allows users to add comments directly from the player itself. Imagine this: the typical toolbar at the bottom includes standard features like seek bar, volume control, play/pause buttons, but wi ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

Dynamically insert textboxes into a form by leveraging the power of the Jade template engine

Looking for a solution to a simple requirement that doesn't seem to have a clear answer online. I need a combobox on my jade page that accepts numbers as input. When the user selects a number, I want the page to refresh and display that many textboxes ...

Creating a button that redirects to an external link in CodeIgniter:

Hello everyone, I'm new here and I could really use some assistance with a problem. I am trying to link the button labeled 'lihat rincian' and each row of tables to redirect to an external link like Here's a snapshot of my datatables ...

Encountering a parser error during an Ajax request

Attempting to develop a login system with PHP, jQuery, Ajax, and JSON. It successfully validates empty fields, but upon form submission, the Ajax call fails. The response text displays a JSON array in the console, indicating that the PHP part is not the is ...

Searching for hidden elements within a div using a filter option

An accordion is located inside a div and a search box has been added to the div with the intention of serving as a search filter. Some accordion elements are visible within the div while others are hidden. The problem arises when trying to make the filter ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

Phonegap app unable to process AJAX post request, functions properly in browser

My AJAX request is encountering issues specifically when tested on the Phonegap App using iOS10. The code I am working with is as follows and functions perfectly in a browser: if($.trim(firstname).length > 0 & $.trim(email).length > 0 & $.t ...

What is the best way to perform a single asynchronous or promise-based fetch request and utilize the retrieved data across multiple functions?

Is there a way to optimize fetching data from an API and use the fetched data in multiple methods within the same service without making redundant requests in the Network? export class MediaService { constructor(private mediaAppApiService: MediaAppApiS ...

The solution for fixing contenteditable is as follows:

I am currently working on a script to clean up pasted text within a contenteditable div. While the script is functioning well for most part, I have noticed that in Firefox, line breaks get removed when the text is copied within or between the divs. Does ...