Can you provide the Angular JS alternative for executing a POST request similar to this Curl command?

Trying to translate a Curl command into Angular JS code has been a challenge for me as a newcomer to AngularJS. This specific instance involves a mobile app built on the ionic framework, which utilizes Angular JS.

The original curl command looks like this:

curl -X POST  -d "username=xxxx&password=xxxx&action=login&view=console"  http://myserver.com/zm/index.php?skin=xml

It functions perfectly when run from the command line.

Within my AngularJS project, I've written the following code:

angular.module('starter.controllers').controller('MonitorCtrl', function($ionicPlatform, $scope,$http)
{
            
console.log("***MAKING REQUEST");
                                                 

//$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
                                                 
 $http({
    url:'http://myserver.com:9898/zm/index.php?skin=xml',
    method:'post',
    headers: {'Content-Type': 'application/x-www-form-urlencoded',
              'Accept': '*/*',
       },
    transformRequest: function(obj) {
       var str = [];
       for(var p in obj)
       str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
       var foo= str.join("&");
       console.log ("****RETURNING "+foo);
       return foo;
    },
       data: {username:'admin',
              password:'xxxx',
              action:'login',
              view:'console'}
       
  })
                                                 
.success (function()
{console.log("****YAY");
})
.error(function(data, status, headers, config)
{
        console.log("***OOPS "+status + " H: "+data);
});
                                                 
                                                
});

While observing the network traffic with httpry, I can see the POST request being sent to the server and receiving a 200OK response with the expected payload, but strangely my success handler is not triggered. Instead, the error handler fires with a status of 0.

Answer №1

The ideal format for the information to be sent in is a JSON object, though this may vary depending on your server setup.

One common method is to use key-value pairs within an object:

data: {username: 'xxxx', password: 'xxxx', action: 'login', view:'console'}

If your server requires input as a string, then you can format it like so:

data: {key: 'username=xxxx&password=xxxx&action=login&view=console'}

Answer №2

After much trial and error, I finally cracked the code

a) It turns out Amir Popovich was spot on - when working with XML, converting JSON to XML is the way to go. The updated code that I shared in my initial question does this perfectly and resolves the issue. However, even after making these changes, my URL requests (post or get) were still failing.

b) To my surprise, the frustrating CORS error I kept encountering was actually due to the fact that I was testing the application on a desktop browser (Safari). Safari was blocking the response unless it had an Accept Origin header included.

c) Strangely enough, everything ran smoothly when I tested the app on my mobile phone. Sometimes technology works in unexpected ways!

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

how to split a string by commas and convert it into an array using angularJS

I need to convert a string, like "12,13", into an array format such as [12,13] in my controller. Even after trying the split function, I couldn't get it to work properly. $scope.mySplit = function(string, nb) { var array = string.split(&ap ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Error occurred in AngularJS service due to incorrect data type

Looking to store the URL of a query in an AngularJS service like this: var mortgageloanService = angular.module('loanstreetIpadAppApp', []); mortgageloanService.factory('updateTable', function($http) { return { getParams: fun ...

Is it possible to continuously refresh a DIV element?

After spending the past 4 or 5 hours scouring Stack and various other resources, I am still unable to find a solution to my problem. The issue at hand involves an Iframe within a page that displays 5 lines of information fetched from a database. This info ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Tips for implementing multi-language URL routing in a Node.js application

I am seeking guidance on how to handle routing for multi-language URLs in Node.js, Currently, I have the following routes set up where each language generates specific routes as shown below. However, with more than 5 languages, efficiency is becoming a co ...

Performance Issues Arise with Rapid Clicking [jQuery]

Having trouble with a gallery script I created that includes thumbnails, a large image, and navigation arrows. When you rapidly click on thumbnails or arrows during the transition, it causes delays in the process. The more clicks you make, the more noticea ...

What could be causing the background color not to change on the HTML page with Bootstrap?

Learning html, bootstrap, and css styling can be a confusing endeavor. Sometimes things don't work as expected, like changing the background color. Despite following what seems like a simple solution after googling, the background color remains unchan ...

Refine the Vuex state with a filter

Currently, I've progressed in my Vue development journey and started exploring the implementation of Vuex for state management. In the past, I had a main Vue component that handled search functionality, an array of items to iterate over, and the iter ...

The Next.js application encounters a crash when trying to integrate Google Firebase authentication

I'm encountering an issue while trying to integrate authentication using firebase (via Google) in my next.js application, and the app crashes consistently. I will provide the code for the auth.js page component, as well as where I set up firebase and ...

Tips for capturing audio in flac codec format using JS/AJAX

Is there a way to record audio in flac codec instead of opus codec? I attempted setting the codec to flac like this: let blob = new Blob(audioChunks,{type: 'audio/ogg; codecs=flac' }); I also tried this: var options = { audioBitsPerSecond : ...

What is the significance of Fawn's statement, "Invalid Condition"?

Despite following the instructions and initiating Fawn as stated in the document, I'm still encountering an error message that says Invalid Condition. Can anyone help me identify what is causing this issue? Thank you to all the helpers. await new Fawn ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

Issue "The only acceptable numeric escape in strict mode is '' for styled elements in Material-UI (MUI)"

Attempting to utilize the numeric quote for quotation marks, I encountered an issue: 'The sole legitimate numeric escape in strict mode is '\0` The snippet of code causing the problem can be seen below: export const Title = styled(Typogra ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

The ThemeProvider does not automatically provide theme injections

After creating a theme using the createTheme method from @mui/material/styles, I attempted to apply this theme using ThemeProvider from the same package. This snippet showcases the dark theme that was created: export const darkTheme = createTheme({ pale ...

Tips for displaying videos with sound when the autoplay has been successfully implemented, but the audio is not working

I've been working on creating a video player with autoplay functionality, but I'm facing an issue with the sound not playing. Here's what I currently have in my code, but it's not behaving as expected: var myaudio = docum ...

What is the best way to include multiple action creators in a single listenerMiddleware in Redux Toolkit?

I am looking to store the current state in my database every time there is a change in any of its properties. I have implemented two middlewares to handle this task, each responsible for dispatching the saveTrip function. Although both middlewares are ide ...