Transform input data from JSON format to FormURL Encoded data by utilizing the transformRequest method

I've been attempting to convert JSON data into formURL encoded data, but I'm encountering issues.

Here's my HTTP post code snippet:

$http.post(API_ENDPOINT.login, credentials, {
    transformRequest: transformRequestAsFormPost
 })

This is my transform request function:

'use strict';

define(['app-module'], function(app) {

$app.info('transformRequest initialized');

return app.factory('transformRequestAsFormPost', function() {

    function transformRequest(data, getHeaders) {
        var headers = getHeaders();
        headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
        return (serializeData(data));
    }

    function serializeData(data) {

        if (!angular.isObject(data)) {
            return ((data === null) ? "" : data.toString());
        }

        var buffer = [];

        for (var name in data) {
            if (!data.hasOwnProperty(name)) {
                continue;
            }

            var value = data[name];

            buffer.push(
                encodeURIComponent(name) +
                "=" +
                encodeURIComponent((value == null) ? "" : value)
            );

            console.log(buffer)

        }
        var source = buffer.join("&").replace(/%40/g, "@");
        return (source);
    }
    return (transformRequest);
});
});

I am struggling to identify the issue. Whenever I pass a JSON object, it returns a string.

Answer №1

As a result of commit 5da1256, the ability for transformRequest functions to alter request headers has been removed. This change was not intended and was not documented, so it should only impact a small number of applications.1

To make a POST request with

Content-Type: application/x-www-form-urlencoded
:

var config = {
  transformRequest: $httpParamSerializer,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
};

$http.post(API_ENDPOINT.login, credentials, config)
  .then(function(response) {
    console.log("SUCCESS");
}).catch(function(response) {
    console.log("ERROR");
    throw 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

Exploring JSON data input in Laravel

Currently, I am utilizing restangular to send a request to the users/login endpoint. Here is how my Laravel route is defined: Route::post('users/login', array('as' => 'login', function () { $input = Input::all(); ...

What is the solution to addressing 404 errors in Karma for an AngularJS project?

When running the "karma:unit" (karma) task, INFO [karma]: Karma v0.10.9 server started at http://localhost:9876/ INFO [launcher]: The browser PhantomJS has been launched INFO [PhantomJS 1.9.7 (Mac OS X)]: Connected on socket lJGhX9DakX2lChvLXtju WARN [web- ...

What steps can I take to ensure that the airplane is able to cast shadows?

I'm trying to make the plane receive a shadow from the sphere, but I seem to be making a mistake somewhere along the way. Does anyone have any ideas on how to fix it? //.................SETUP................// import { WebGLRenderer, Perspecti ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

Guide on extracting XML information from a website and presenting it in a UITableView

I've got a good handle on generating and utilizing JSON data in UITableView, as demonstrated by this sample JSON data link However, for my latest project, the client has provided XML data instead. The sample data can be found here: I'm eager to ...

Creating a Bootstrap dropdown without relying on jQuery can be achieved by using only

I am looking to implement a Bootstrap dropdown menu without relying on jQuery. <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Dropdown <span class ...

Is there a way for me to collaborate on a footer control with a different website?

Is it possible to seamlessly incorporate a footer from one website into another? Ideally, I want the footer HTML (and styles) to be dynamically inserted into different web pages. The common workaround is using an iframe, but this causes navigation issues ...

Formik's handleSubmit function appears to be malfunctioning

I have encountered a puzzling issue with Formik implementation in my two components. Despite implementing Formik in the same way for both components, I am facing a problem where `handleSubmit` works in one component but not in the other. You can check out ...

Send a JSON object to a C# ASP.NET WEB API endpoint

I'm having trouble sending a JSON object in the body of my HTTP message. I've attempted the following: $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; but the issue p ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

Creating a Mongoose schema to store an array of objects, where updates will automatically add new objects

const mongoose = require('mongoose'); module.exports = mongoose.model('GridModel', { Request_Id : { type : Number, required : true }, viewStudents : { type : Array , default : [] } }); The mongoose model above needs to b ...

What is the best way to handle multiple queries in NightmareJS?

The following JavaScript code utilizes NightmareJS to search a website for 3 posts and retrieve the username of the post uploader. var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }); var inputArray = [198,199,201]; ...

Utilizing jQuery Autocomplete with JSON to fetch consistent results

I have this specific code snippet within my index.php file: $(document).ready(function(){ $("#searchInput").autocomplete({ source: "getResults.php" }); Furthermore, the getResults.php script is as follows: <?php $result = array(); array_push($result, ...

Determine the width of the device screen and execute specific JavaScript files based on the screen size

I am working on two different pieces of JavaScript code. My goal is to first detect the width of the screen, and then dynamically choose which JS file to run based on this width. Can someone guide me on how to achieve this correctly? $(document).ready(f ...

Purchasing products does not seem to work properly when using a combination of a JSON file and a form

I am currently working on a webshop for a school project using PHP. I have encountered an issue where products added to the cart are not actually getting added. Despite spending hours trying to troubleshoot, I have been unable to find a solution. I am reac ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Displaying an error message in a spreadsheet cell

Issue The problem arises when viewing the exported excel file where undefined is displayed. However, upon investigation, there are no empty array indexes causing this confusion. Solution Attempt const joinDate = new Date(obj.date); let snap = [ obj. ...

Detecting a mobile device when using NextJS can be accomplished by using user

With so many topics and questions on Stack Overflow, I am struggling to find the most efficient solution for detecting mobile devices. I have two components - one designed solely for desktops and another for mobile devices. {isMobile? (<SecondComponen ...

JavaScript file system function not functioning according to its designated purpose

I have a basic script to write a JavaScript list to a JavaScript file. // Using the fs module to access // the writeFile function. var fs = require('fs'); // Start by overwriting any existing file with the beginning of the list fs.writeFile(&apo ...

Utilizing NextJS Image Component in Conjunction with Auth0

I have been working on integrating auth0 with nextJS and encountered an issue with the next.js Image component. Let's review the code snippet: import Image from "next/image" import { useUser } from "@auth0/nextjs-auth0" export def ...