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

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Is it possible to activate multiple animations simultaneously within a single div using UIKit?

I recently started developing a to-do web application and was looking to enhance its appearance with some animations using UIKit. Currently, I have an animation that toggles when the todo-items are brought into view: <div class="todo-items uk-anim ...

Unable to link to '' because it is not recognized as a valid attribute of '' in Angular 2

I encountered an exception while working on my Angular 2 project and I'm struggling to figure out the cause. Below is the snippet of my code: ts: import {Component} from "@angular/core"; import {GridOptions} from "ag-grid"; import {RedComponentComp ...

Having trouble with JavaScript function returning false?

I am trying to call a JavaScript function on an ASP.NET button client click event and want to prevent postback. The function is working, but it is not preventing the page from posting back. Here is my JavaScript code: function User2Check() { v ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

Run the .map() method at regular intervals of 'x' seconds

I have a certain function in mind: function fetchDesign (items) { items.map(item => item.classList.add('selected')) // additional code here } Is there a way to trigger item.classList.add('selected') every 2 seconds, while ensu ...

What steps can I take to guarantee that a directive's link function is executed prior to a controller?

Our application features a view that is loaded through a basic route setup. $routeProvider .when('/', { template: require('./views/main.tpl.html'), controller: 'mainCtrl' }) .otherwise({ re ...

Learn how to securely transmit data using basic authentication in Node.js with the node-fetch module

Having trouble with this code. I am facing an issue where a "post" request with basic authentication returns a 200 status, but no response data is received. Surprisingly, when the same code is executed without auth credentials, it works perfectly fine. l ...

Issue with Many to Many Relation Query in Objection JS, Postgres, and Express Resulting in 'TypeError: Cannot Read Property 'isPartial' of Null' Error

I have a challenge connecting the 'products' table to the 'tags' table using a many-to-many relationship structure with the 'products_tags' table. Upon executing const product = await Product.relatedQuery('tags').fi ...

The property 'dateClick' is not found in the 'CalendarOptions' type in version 6 of fullcalendar

Below is the Angular code snippet I am currently using: calendarOptions: CalendarOptions = { plugins: [ dayGridPlugin, timeGridPlugin, listPlugin ], initialView: 'dayGridMonth', headerToolbar: { left: 'prev today next' ...

Using a Javascript hyperlink to trigger a POST request in Python

I am currently developing a web scraping and automation tool that requires the use of POST requests to submit form data. The final action involves using the following link: <a id="linkSaveDestination" href='javascript:WebForm_DoPostBackWithOptions ...

React's connect method is causing issues with my test case

Attempting to create a test case for my jsx file... Took a sample test case from another jsx file... The other file does not have the connect method... But this new file contains the connect method... Believe this is causing issues with my test case... Any ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

Applying VueJS filters to refine object values

Is there a way to verify if the value of "startAt" is present in an object and return its corresponding ID? Here is the object in question: [{ "id": "1234567", "createTimestamp": "2020", "name": { "action": "", "allDay": false, "categor ...

Move each four-character IT value to a new line

const maxNumLength = 4; event = jQuery.Event("keypress") event.which = 13 $('#input').on('input focus keydown keyup', function() { const inputValue = $(this).val(); const linesArray = inputValue.split(/(&bsol ...

Model updating with the addition of an item and triggering a secondary ng-repeat for refreshing

As I was working on the phone tutorial, I found myself pondering how to implement a specific use case. The browser renders a list of phones. When the user clicks on add phone for one of these phones, the function addItem is triggered and adds that phone ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

What is the best way to simultaneously update the model and view values in an Angular directive?

My apologies if directives are not my strong suit! Within this simple attribute-only directive, the primary goal is to automatically convert a string in a field to an HH:mm format upon blurring the field. The directive code is as follows: (function () { ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...