Angular receives error when making $http calls that return a 200 response

I am facing an issue with a code snippet used in an Angular service:-

var formData = function (data) {
   var fd = new FormData();
   angular.forEach(data, function (value, key) {
      fd.append(key, value);
   });
   return fd;
}

var updateUserPic = function (profilePic, callback, userId) {
   var userId = userId || FRAME_API.proxyUserId; // jshint ignore:line
   if (!_.isFunction(callback)) {
      throw new Error('You must provide a callback function.');
   } 
   $http({
      method: 'POST',
      url: '/Learn/PostUserProfile.ashx?action=profilepic&userid=' + userId,
      data: {up_picfile: profilePic},
      transformRequest: formData,
      headers: { 'Content-Type': undefined}
   }).success(function (data, status, headers, config){
      callback([data, status, headers, config]);
      return;
   }).error(function (data, status){
      console.log([status,data]);
      callback(false);
      return;
   });
};

When checking using the Network tab in Chrome's Developer Tools, I can see that the response is 200 OK. However, the issue arises as the error callback is always triggered, even though the status is 200. Furthermore, the data and status parameters are received as undefined.

Could there be any specific reason for this behavior?

The server response contains the following information:

{status: 'success', path: 'assets/profile/profilepicture.png'}

Additionally, it is important to note that I do not have control over this response as it originates from a vendor script running on the server which is inaccessible to me.

Answer №1

I successfully converted the response to valid JSON format using a custom response transformer:

var customTransformer = function (responseData) {

   return responseData.replace('status', '"status"')
                     .replace('\'success\'', '"success"')
                     .replace('path', '"path"')
                     .replace('\'assets/profile/profilepicture.png\'',
                              '"assets/profile/profilepicture.png"');

};

After applying this transformation, everything worked smoothly.

Answer №2

Here is an example of the data that will be returned:

{ "status": "success", "path": "assets/profile/profilepicture.png" }

Please make sure to use double quotes instead of single quotes.

Answer №3

When troubleshooting my issue, I discovered that the server was sending back a "File Not Found" message instead of the expected JSON response that Angular's $http function required. This caused confusion because despite receiving a 200 OK status code, the .error section of the http method was being executed.

To resolve this issue, I made sure to have the server return a JSON Object as the response.

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 is the process for updating the internal TypeScript version in VS Code?

When using VS Code, I noticed it comes with its own TypeScript version: Is there a way to update this? The current version is 4.9.3. https://i.sstatic.net/vEx85.png ...

Adjusting the transparency of the object's interior

I used the side property to give my object an interior, but it also reflects the exterior: let material = new THREE.MeshStandardMaterial({side: THREE.DoubleSide}); https://i.sstatic.net/oikad.png https://i.sstatic.net/Vb03K.png Is there a way to red ...

At Eclipse, an error is showing up indicating that the attribute name (ng-model

My Eclipse is showing an error related to the "ng-model" tag When I try to save the file, Eclipse warns about the ng-model attribute: <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Learning AngularJS</ti ...

Redirect to URL using Ajax upon successful completion

I'm facing an issue with my function as it doesn't redirect after a successful operation. I'm not sure why the redirection is not happening consistently. Sometimes, adding ...href after e.preventDefault(); seems to work. $('#nadwozie&a ...

Error encountered during Yarn installation process: The tunneling socket was unable to be established due to a connection refusal on localhost at port 80

I have a Next.js app that needs to be built on our company servers before deployment. We use a proxy, and I've configured yarn to use the proxy as well. yarn config set proxy http://xx.xxx.xx:xxxx yarn config set httpsProxy http://xx.xxx.xx:xxxx yarn ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

Whenever the refresh parameter is activated on the initial jsp page, it triggers a refresh for all jsp pages

Currently, I am facing an issue where I am trying to refresh just the starting page named "1.jsp". The goal is to call some functions on this page and then redirect to another jsp page, "2.jsp", once a certain condition is met. However, I have noticed that ...

employing express.json() post raw-body

Within my Express application, I am aiming to validate the length of the request body and restrict it irrespective of the content type. Additionally, I wish to parse the body only if the content type is JSON. How can I go about accomplishing this? Curren ...

How can MongoDB insert a field that corresponds to a JavaScript variable?

I'm having trouble adding a new field to MongoDB. The database accepts my Javascript variable as data, but not as the name for the new field: function appendInformation(question, answer) { Sessions.update({ _id: Id }, { question : answer }); } T ...

Prevent AngularJS UI Router view from refreshing upon tab change

In my application, I am utilizing AngularJS UI routing to implement tabs for a better user experience. There are several tabs within the application, each containing various input fields. One issue I am facing is that whenever a user switches tabs whil ...

The xmlhttp object parameter is not defined. JavaScript AJAX

As a newcomer to javascript and ajax, I am trying my best to understand it all. I followed a tutorial to write this code, but I can't seem to figure out what I did wrong. If you click here, you can see the live version. The error message that Firebug ...

Steps for adding a favicon to Content-Type: application/json

In my implementation using node.js, I have an API that returns a response with Content-Type: application/json. Here is an example: module.exports={ api: (req, res) => { let data = {"data": [1, 2, 3]}; res.status(200).json(d ...

Changing dimensions of cube on stable base

I'm currently working on a project involving a dynamic cube that can be scaled in real time by adjusting its mesh. However, I'm facing a challenge in keeping the cube fixed to the floor while changing its height. Here's a snippet of the code ...

Having trouble getting my javascript integration to work in a Django template - any ideas on what could be causing

As a newcomer to Django, I'm working on creating a small webpage that displays a chart using Chart.js. My goal is to load the JavaScript file statically. To achieve this, I have set up a basic HTML file named data_table.html and included a "static" fo ...

Using AngularJS to incorporate multiple ng-apps on a single webpage

I'm new to Angular JS and I've started creating some basic samples. However, I've encountered a problem that I can't seem to solve. So far, I have created 2 modules and 2 controllers: shoppingCart -> ShoppingCartController namesLis ...

Utilizing npm packages from third-party sources within a custom extension for personal use (not intended for distribution)

Exploring the idea of developing a basic Firefox extension that involves external modules such as Firebase and Cheerio, but there doesn't seem to be much information available on this topic. I noticed there are legacy options like jpm, but they'r ...

Discovering the Cookie in Angular 2 after it's Been Created

My setup includes two Components and one Service: Components: 1: LoginComponent 2: HeaderComponent (Shared) Service: 1: authentication.service Within the LoginComponent, I utilize the authentication.service for authentication. Upon successful authent ...

Creating a foolproof image polling platform: A step-by-step guide

I'm in the process of creating a webpage on my site that allows users to view a collection of images. The goal is for each registered user to choose one picture as their favorite, increasing that picture's score by one. The image with the highest ...

What is the proper way to type a collection and put it into action?

I am looking for a way to create an object that mimics a set. Specifically, I want the transaction id to act as a key and the transaction details as the value. To achieve this, I created the following: type TransactionDetail = { [key: TransactionId]: Tra ...

Step-by-step guide on implementing a real-time data array counter in React js

I am attempting to create a function that continuously generates new data arrays with an increasing counter. Each second, a new array should be added with the next number in sequence. data={[ { x: 1, y: 1 }, { x: 2, y: 2 }, ...