AngularJS HTTP request not functioning properly with duplicate requests in Postman

My postman request is working fine, but the equivalent in angularJS isn't.

I'm able to get the response I need in Postman, but for some reason, it's not working in Angular.

var settings = {
      "async": true,
      "crossDomain": true,
      "url": "http://197.157.93.110/Apiv1/token",
      "method": "POST",
      "headers": {
        "cache-control": "no-cache",
        "postman-token": "c76c4b6a-9a69-23dd-0171-8e6cbacd7944",
        "content-type": "application/x-www-form-urlencoded"
      },
      "data": {
        "grant_type": "password",
        "UserName": "user1",
        "Password": "password"
      }
    }

    $.ajax(settings).done(function (response) {
      console.log(response);
    });

This is what my Angular code looks like:

services.factory('documentService', ['$http', function($http){
            return {
                    getToken:function(grant_type,user,password){
                        return $http({
                                method:"POST",
                                url:"http://197.156.93.110/Apiv1/token",
                                headers: {
                                            "cache-control": "no-cache",
                                            "content-type": "application/x-www-form-urlencoded"
                                  },
                                data: {
                                    "grant_type": grant_type,
                                    "UserName": user,
                                    "Password": password
                                  }         
                        });
                    }
                ,

When I try to use this, I keep getting a Bad Request error with a code of 400.

I'm trying to call the promise later in my code like this:

documentService.getToken("password","user1","password").success(function(token){
        $scope.access_token=token.access_token;
        $scope.userName=token.userName;
        $scope.token_type=token.token_type;
        $scope.message={"message":"success"};
                $interval(function () {
                    $scope.message = "";
                }, 10000);
                //call get documents if only access token is success


    }).error(function(err){
        $scope.message=err;
        $interval(function () {
            $scope.message = "";
        }, 10000);
    });

Answer №1

Looking at the code snippet you provided, it's clear that you have set up an ajax call with a callback function for the Postman block to handle the success and returned data. However, this same handling is missing from the AngularJS example.

In Angular, $http operates on promises. The Angular documentation here specifies that $http should be used with a .then() handler like so:

var settings = {
   //POST settings
}
$http(settings)
.then(function successCallback(response) {
    // This callback will be executed asynchronously
    // once the response is available
    console.log(response);
  }, function errorCallback(response) {
    // Executed asynchronously in case of an error
    // or if the server returns a response with an error status
    console.log(response);
  });

Answer №2

After making some adjustments to the request and removing the cache control in the header, everything started working smoothly for me.

Here is the final code:

services.factory('documentService', ['$http', function($http){
return {
        getToken:function(grant_type,user,password){
            return $http({
                    method:"POST",
                    url:"http://197.156.93.110/Apiv1/token",
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
                     transformRequest: function(obj) {
                        var str = [];
                        for(var p in obj)
                        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                        return str.join("&");
                    },
                    data: {
                        "grant_type": "password",
                        "UserName": "user1",
                        "Password": "password"
                      }         
            });
        }
    ,

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

Encountered an error while attempting a GET request to 'http://localhost:3000/': The resource failed to load, resulting in a net::ERR_CONNECTION_REFUSED error in delete.js

Every time I attempt to GET '/' through my express server, I encounter an error message indicating "Failed to load resource: net::ERR_CONNECTION_REFUSED ... delete.js". This issue typically arises when I try to submit a form from http://localhost ...

Using Typescript to change a JSON array of objects into a string array

I'm currently working with the latest version of Angular 2. My goal is to take a JSON array like this: jsonObject = [ {"name": "Bill Gates"}, {"name": "Max Payne"}, {"name": "Trump"}, {"name": "Obama"} ]; and convert it into a st ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...

In search of a suitable approach for handling errors generically in Angular, using a JSON response received from Rails

Currently in the process of developing an application that is structured as a Rails server app providing RESTful APIs to the client. The Rails server utilizes RABL, while the client consists of an Angular JS application making standard $http calls (such as ...

Determine the hue of a specific location on a geometric surface

I'm currently working with THREE.js for my scene rendering and I have a complex question - how can I retrieve the color of a specific point on a geometry face? When I mention color, it's not just the face or material color that I'm interest ...

Is there a way to redirect the user to a different page without refreshing the page during navigation?

Utilizing javascript, ajax, and jquery to dynamically load content from PHP files without refreshing the page has been a successful venture. However, I am facing a challenge in creating a hyperlink within one of the loaded contents that redirects the user ...

Loading components dynamically with axios is a valuable feature

Can this be achieved? There is a spinner component. axios: action() { SPINNER (component) -- activate axios.get('/store', { params: { something } }) .then ((resp) => { SPINNER (component) -- ...

Problem with Angular-UI Bootstrap Tooltip

It seems like due to the current structure of the page, the tooltip functionality is not functioning properly. index.html <div class="main-navigation"> <div rt-tool-menus-"menus" selected="selectedMenus" tooltip="{{appController.displayName}} ...

Enhance efficiency with Bootstrap typeahead prefetch capability

Currently, I am utilizing the Bootstrap typeahead API to generate a real-time search feature. The source option is quite useful as it enables an AJAX call to retrieve data from the server. However, I am interested in preloading the source upon page load a ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

Navigating back to the original page after venturing to a different one - react

In the header of each page, there is a 'Back' button that allows users to navigate back to the previous page. The function handleGoBack() is responsible for this: import React from 'react'; import { Button, Typography } from "@mate ...

Adding a Resource Bundle to a Vue project

I am looking to integrate the ResourceBundle package into my Vue project. After installing it with the following command: npm install resource-bundle I discovered these exported functions in the index.js file of the ResourceBundle package: export functi ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

template strings receive null value

I am currently facing an issue with the execution of certain template literals in my jQuery functions. Although some are functioning as expected, there is a specific block that is not being executed. function viewUserDetails(data) { // retrieves integer v ...

Strategies for resolving the problem of null values from getParameter() being passed from AJAX to servlet

After reading numerous answers on Stack overflow, I have tried various solutions to fix this issue without success. My goal is to send a JavaScript variable to a servlet using AJAX within an else statement in JS. However, I keep receiving null in the alert ...

Monitoring and recording Ajax requests, and retrying them if they were unsuccessful

As a newcomer to Javascript, I'm diving into the world of userscripts with the goal of tracking all Ajax calls within a specific website. My objective is to automatically repeat any failed requests that do not return a status code of 200. The catch? T ...

What is the best way to access the attributes of a particular object following a triggered event?

I'm a bit unsure if my title makes sense, so allow me to explain. In a nutshell, I have 2 li elements within a ul list. What I aim for is that when one of these li elements is clicked, the text within that particular li is retrieved, and then an obje ...

Issues arise when Angular Meteor fails to load the UI-Router properly

Currently, I am exploring the integration of ui-router for routing within a meteor-angular application. My reference point is the meteor Whatsapp tutorial which can be found here Below is the relevant code snippet related to ui-router implementation: log ...

The proper management of AngularJS data models is essential for efficient operations

As I search through various resources online, I am discovering numerous methods for managing the data model utilized in our Angular templates. However, each source only offers a glimpse of the overall picture. In a complex application, it is crucial to con ...

What steps can I take to streamline and simplify this tab controller code?

I'm looking to simplify this jQuery code because I feel like there's repetition. As someone new to JavaScript and jQuery, I've created two tabs with their respective containers containing miscellaneous information. My goal is to have each co ...