Angular factory encounters 405 error with API $http delete request

In my factory, everything was running smoothly with regular ajax syntax from the controller.

function endAgentSession(sessionData, tokenData) {

            var sessionId = sessionData.data.sessionId,
                access_token = tokenData.access_token,
                baseURI = tokenData.resource_server_base_uri,
                endAgentSessionPayload = {
                    'sessionId': sessionId,
                    'forceLogOff': true,
                    'endContacts': true,
                    'ignorePersonalQueue': false
                    };

            console.log(sessionId, "sessID");


            return $http({
                'url': baseURI + 'services/v6.0/agent-sessions/' + sessionId,
                'type': 'DELETE',
                'headers': {
                    //Use access_token previously retrieved from inContact token service
                    'Authorization': 'bearer ' + access_token,
                    'content-Type': 'application/json'
                },
                'data': endAgentSessionPayload
            }).then(function(res){
               return res })};
        }

A 405 error occurs when I call the endAgentSession function from the controller using an ng-click.

 $scope.endAgentSession = function(){
    agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};

Something seems to have gone wrong. It was functioning properly with ajax in the controller, but when moved to the factory and utilized a promise, it breaks down.

Interestingly, it shows that it's requesting a GET request in Network.. [![enter image description here][1]][1]

Here is the full controller:

csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', 'agentFactory', '$timeout', function ($scope, $http, $document, $resource, agentFactory, $timeout) {

$scope.agentStatePayload = {};
$scope.sessionData = {};
$scope.tokenData = {};
$scope.startSessionPayload = {
    'stationPhoneNumber': '2223222222',
    'inactivityTimeout': 0,
    'inactivityForceLogout': 'false'
};

$document.ready(function () {
    $scope.tokenData = agentFactory.getToken();
    console.log($scope.tokenData);
});

agentFactory.startSession($scope.startSessionPayload, $scope.tokenData).then(function(res){
    console.log("sessionId", res);
    $scope.sessionData = res;
});



$scope.endAgentSession = function(){
    agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};


}]);

Everything appears to be functioning correctly, except for the endSession now..

Answer №1

It was clear to me now that every instance you referenced

the typical ajax syntax from the controller

You were actually referring to your prior use of jQuery's $.ajax.

An important distinction is that in Angular's $http, the property for specifying the request method is method, not type.

To streamline this process further, you could utilize

return $http.delete(baseURI + 'services/v6.0/agent-sessions/' + sessionId, {
    headers: {
        Authorization: 'Bearer ' + access_token,
    },
    data: endAgentSessionPayload
});

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

Include the HTTP header in a GET request for an HTML hyperlink

Within my HTML code, I am using an <a> tag that will trigger a 302 redirect when clicked. However, I need to incorporate some HTTP headers into this GET request. Is there a way to achieve this without including the headers in the href attribute? Tha ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...

Ways to resolve the array to string conversion issue in PHP

In my PHP project, I am dealing with a dynamic array and trying to store the array result in a variable. However, I encountered an error: array to string conversion while coding. <?php require_once('ag.php'); class H { var $Voltage; ...

What steps should I take to integrate my Node.js code into a website successfully?

I have a node.js code that works perfectly in the terminal. How can I display the console.log output on localhost and later on Heroku? Since I am still a beginner, I find express challenging. Do you think I should use it? I also tried Browserify. const p ...

Leveraging the httponly cookie for transmitting JWT token between a Node REST API and a Vue.js SPA

I am currently in the process of developing a web application that utilizes a Vue.js frontend along with a Node REST API built using express. I am facing a challenge in implementing authentication, particularly in striving for a stateless approach by utili ...

"Implementing form validation, utilize JavaScript to dynamically insert an unordered list containing list items (li) into a specified div

When validating a login form, I encountered a challenge with displaying errors using an unordered list for each validation error such as an incorrect username or email format. I am familiar with input validation but struggling with incorporating an unorder ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

When attempting to insert data retrieved from axios into a table within a React component, the data is coming back as

Hi there! Currently, I'm in the process of developing an application that retrieves data from an API and my goal is to display it in a Material UI Table within a React environment. Strange issue I'm encountering: when I use console.log to check ...

There was an issue with the NextJS axios request as it returned a status code

I'm currently in the process of developing an application with NextJS and Strapi In my project, I am fetching data from Strapi using Axios within NextJS Next: 14.0.4 Axios: ^1.6.5 Strapi: 4.17.1 Node: 18.17.0 Here is the code snippet: import axios f ...

What is the method for generating a 4-digit input sequence without the use of JavaScript?

When I enter a four-digit number (verification code) in the form input, the structure of the PIN-code breaks down after entering the fourth digit. The text pointer moves to the fifth character even though I have defined only four characters. Is there a CS ...

The extent of locally declared variables within a Vue component

Within this code snippet: <template> <div> <p v-for="prop in receivedPropsLocal" :key="prop.id" > {{prop}} </p> </div> </template> <script> export default ...

Tips for utilizing the 'contains' feature within web elements with Java Selenium WebDriver?

In my current project, I am facing a challenge with two specific elements: one is a string formatted as ABC £12,56 and the other is a box called "Cashbox" that should be 15% of the value of the string. However, when attempting to locate the CSS for both e ...

Enable the ability to upload multiple images on a single page using droparea.js

I am currently utilizing droparea js for uploading images. However, I have encountered an issue where if I try to upload an image in one of the upload menus, it ends up changing all four upload menus simultaneously. <div class="col-md-12"> ...

The attempt to cast to a number for the value of "[object Object]" at the specified path failed in mongoose

My schema is structured like this: module.exports = mongoose.model('Buyer',{ username: String, password: String, email: String, url: String, id: String, firstName: String, lastName: String, credit: Number, }); Wh ...

I am required to filter out any child elements from a find() operation

HTML: <ul> <li class="listExpandTrigger"><h3>2010 - present</h3></li> <li class="listCollapseTrigger"><h3>2010 - present</h3></li> <li> <ul class="volumeList"> <l ...

Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could ...

React Braces Dilemma

I'm a bit embarrassed to admit it, but I'm struggling with writing something simple in React using JSX. Despite searching online and consulting various resources, including the official React documentation, I am still unable to grasp the concept. ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

Is there a way to route an angular request through a spring filter prior to validation?

I'm currently working on implementing an XSS Filter in a backend application (built with JAVA and Spring). The goal is to validate input values from a frontend app (AngularJS) against the filter before proceeding to validate the rest of the content. ...

gulp-open not functioning properly following the use of createWriteStream

I am utilizing gulp, gulp-eslint, and gulp-open to generate a report detailing ESLint outcomes. The linting and file creation processes function correctly; however, the task aimed at opening the file containing my report encounters issues. gulp.task(&apos ...