Working with HTTPS in Angular: A guide to using $http

Can anyone provide guidance on how to handle https + cross-domain URL using $http?

I managed to solve my issue using $.ajax, but I prefer using $http because I have an $http interceptor set up to automate certain processes.

I've checked out related posts [link1, link2, link3] but none of them have resolved my issue.

I've attached a screenshot of my console for reference.

The strange thing is that $http is using the OPTION method instead of POST as specified.

Below is a snippet of my code:

$http({
    method: 'POST',
    url: '/HearingCentre',
    data: {
        Type: ['P', 'V']
    },
    success: function (res) {
        console.log(res);
        d.resolve(res);
    },
    error: function (res) {
        console.log(res);
        d.reject(res);
    }
 });

NOTE: I'm utilizing an $http interceptor that appends the base API URL to the specified URL.

$.ajax version

$.ajax({
    method: 'POST',
    crossDomain: true,
    url: 'https://ahtstest.hearing.com.au/services/api/HearingCentre',
    data: {
        Type: ['P', 'V']
    },
    success: function (res) {
        console.log(res);
    },
    error: function (res) {
        console.log(res);
    }
});

Does anyone have a solution to this issue?

Answer №1

var appUser = angular.module('appUser', []);
    appUser.controller('UserController', function ($scope,$http) {

        //making a server call using Angular 
        $scope.makeServerCall = function() {
                var url = '/root/jsp/catalog/xml/getJsp.jsp?PatientId=9175;
                $http({
                    crossDomain: true,
                    xhrFields: {withCredentials: false},
                    headers: {'Accept': 'application/json','Content-Type': 'application/json'},
                    method: 'GET',
                    url: url
                }).then(function(response) {
                    console.log("Request successful: "+JSON.stringify(response));
                },function(response) {
                    console.log("Request error:   "+JSON.stringify(response));
                });
        };
  }

Ensure that your server side allows cross domain requests. For example, in Spring MVC, you can add a filter and configure cross domain requests as shown below. If you are using a different language like PHP, you will need to set the appropriate response headers.

Server filter for Spring MVC

@Component
public class EcwCORSFilter implements Filter {

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                HttpServletResponse response = (HttpServletResponse) res;
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With,isAjaxRequest");
                chain.doFilter(req, res);
        }

        public void init(FilterConfig filterConfig) {
        }

        public void destroy() {
        }

}

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

What happens when an AJAX request is aborted in jQuery - does it trigger the done or fail

I am struggling to grasp the concepts of $.ajax, .done, and .fail. When I initiate my ajax call, I store it in a variable. During the next ajax call, I check if the variable is defined and then use abort. I'm unsure whether .abort() triggers .done ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

What is the most effective way to loop through an object containing DOM selectors as values, and subsequently utilize them to assign new values?

I have a function that takes an object retrieved from a database as its argument. My goal is to display the values of this object in a form by associating each value with a specific DOM selector. Here is the code snippet where I achieve this: function pai ...

Check for pattern using JavaScript regular expression

Utilizing ng-pattern to validate a regular expression. The pattern must include 3 letters and 2 numbers in a group. For example: G-31SSD or G-EEE43 Currently, the pattern only matches the second example. ng-model="newGroup.groupCode" ng-pattern="/^&bso ...

Struggling with navigating segmented dropdown buttons

I was following a tutorial on Udemy to learn about inputs and dropdown buttons for bootstrap. Everything was going well until I attempted to create a simple selection of albums for one of my favorite artists. The buttons kept separating when I tried to cen ...

To make table headers remain stationary as the data scrolls with JavaScript

When using Explorer, I was able to fix the "thead" part of my table while scrolling by using CSS expressions. The following CSS code snippet showcases how it's done: .standardTable thead tr { position: relative; top: expression(offsetParent.scrollTo ...

Achieve filter dominance by implementing an AngularJS filter name override

In my AngularJS application, I have an array of data that is displayed using ng-repeat. The data is filtered and paginated based on user inputs, with the filtering criteria set by a function in the controller. What I'm looking to do now is override t ...

Blur-triggered form validation

Within my webpage, I'm facing an issue with 5 input fields that need to be validated on blur. Instead of relying on alert boxes, I aim to display either an error or success message through DOM scripting. Despite trying various codes, nothing seems to ...

Exploring the Versatility of Axios

Today, I implemented an AJAX request using Axios in JavaScript to submit form data. While the requests are being sent successfully, it seems that the backend is not able to receive the username and password information from the frontend. What could be ca ...

What is the process for incorporating synchronous tasks within an asynchronous function?

const fs = require('fs') const readline = require('readline') const stream = require('stream') const rl = readline.createInterface({ input: fs.createReadStream('logs.txt') }) var uniqueItems = new Set() // ASY ...

The datepicker is refusing to update the date format

I've been attempting to adjust the date format for my datepicker, but it refuses to change. Below is the code I'm using: $(document).ready(function() { $('#dateselect').datepicker({ format: 'dd/mm/yyyy', o ...

Unidentified entity triggering an error in the console

It seemed like there wasn't anything quite like this before... at least not that I could understand with my limited experience. I was experimenting with creating a global object that contains methods, including instructions for handling AJAX requests ...

What is the best way to loop through strings in a request object?

I am currently working with Express and need to scan the POST requests to create an array called openingTimes. After that, I want to generate a MongoDB document based on the user inputs. The code snippet below is functional, but I am looking for a way to ...

How do I customize the HOME page in JHipster to display unique content based on user roles?

I am currently developing a JHipster project where I need to display different home pages based on the role of the user logging in. Specifically, I am utilizing Angular 1.x for this project. For instance, I have roles such as ROLE_ADMIN and ROLE_USER, each ...

Troubleshooting undefined results when dynamically loading JSON data with $scope values in AngularJS

My input field is connected to the ng-model as shown below. <div ng-app="myApp" ng-controller="GlobalCtrl"> <input type="text" ng-model="FirstName"> {{FirstName}} </div> In my controller, console.log $scope.FirstName shows m ...

Hover over to disable inline styling and restore default appearance

There are some unique elements (.worker) with inline styles that are dynamically generated through Perl. I want to change the background when hovering over them and then revert back to the original Perl-generated style. The only way to override the inline ...

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Retrieving JSON Data from an API with JavaScript/jQuery

Having some trouble with JSON parsing using jQuery and JavaScript. I'm trying to fetch weather information from the open weather simplest API, but for some reason it's not working. When I hardcode the JSON data into a file or my script, everythin ...

What is the best method for sending variables to the `script.` block in Pug?

I am encountering an issue with the code in my index.pug file doctype html html head title= title body script(src=`${source}`) script. for (var event of events){ VClient.Event.subscribe(event, createDiv); } This is how ...

Only initiate a reload once the Post request has been successfully completed

$('.active-per').click(function () { var text = $(this).data('value'); $('.active-per').removeClass('active'); if (text == "t" || text == "n" || text == "c" || text == "r") { $(this).addClass("ac ...