Performing an HTTP POST request in Angular 2

After starting my work with Angular 2 and TypeScript, everything was going great. However, I encountered an issue when working with a REST API (POST) where the console log displayed

Response {_body: "", status: 204, statusText: "Ok", headers: Headers, type: 2… }
. Despite passing the correct parameters for logging in, this is my code:

 authentification(){
        var headers = new Headers();
          headers.append('Content-Type', 'application/x-www-form-urlencoded');
        // headers.append('Content-Type', 'application/json');
       return this.http.post(this._postUrl,JSON.stringify({username:"abc",password:"abc"}),{headers:headers});
    }

And here is my web service:

 @POST
    @Path("/admin")
    @Consumes("application/x-www-form-urlencoded")
    public User getDate(@HeaderParam("username")String username,@HeaderParam("password")String password) throws Exception{
        try {
            String passwordC =  AESCrypt.encrypt(password);
            User u = userService.login(username, passwordC);
            return u;
            
        } catch (Exception e) {
            return null;
        }
    }

It seems like the problem lies in the parameter difference between the string in my web service and JSON in Angular. Can anyone help me with this? Thank you.

Answer №1

When dealing with form-urlencoded content type, it is necessary to send data in query string format containing key=value pairs. One way to accomplish this is by utilizing the URLSearchParams class within the http module. In your particular scenario, the code snippet may appear similar to the following:

authenticateUser() {

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    var params = new URLSearchParams();
    params.append('username', 'abc');
    params.append('password', 'abc'); // .toString() => username=abc&password=abc

    return this.http.post(this._postUrl, params.toString(), {headers});
}

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

Is it possible to duplicate a div element and then make changes to both the original and the clone using a single button

I am dealing with an element that has three sub-elements element1, element2, and element3. When I press the button1 command, it filters element1. When I press the button2 command, it filters element2. How can I clone this element and manipulate both th ...

Unable to verify the authenticity of every file I choose to upload

Currently, I am in the process of learning how to develop a mean stack app, specifically focusing on creating an ecommerce type application. The main issue that I have encountered revolves around image uploading. My goal is to upload multiple files simult ...

Exploring Angular 9: Harnessing the Power of Fork Join with an Array of

I have a challenge where I need to send multiple API requests to an endpoint by iterating over an array of values To handle this, I decided to use rxjs library and specifically the forkJoin method //array to keep observables propOb: Observable<any>[ ...

I'm having trouble getting my PrimeNG Calendar component to line up correctly

::ng-deep p-calendar.calendar-control > span > input.p-inputtext { border: 1px solid black; background: #eeeeee; text-align: center !important; } The content is not properly centered. <p-calendar dateFormat="mm/dd/yy&qu ...

Struggling to bring in components in ReactJS

My journey with ReactJS has just begun, and I've encountered some issues with the code that I believe should work but doesn't. To start off, I set up a new ReactJS project using the npm command create-react-app. Following this, I installed Googl ...

The image will remain static and will not alternate between hidden and visible states

I am facing a challenge trying to toggle an image between 'hidden' and 'show' My approach is influenced by the post on How to create a hidden <img> in JavaScript? I have implemented two different buttons, one using html and the ...

Building a Database in a Node.js Express Application Using Jade and JavaScript

UPDATE After conducting extensive research, I have discovered that the web application utilizes the node-db-migrate package. Within the migration folder, there are two migrations containing table creations. As I recently git cloned the project, it is evid ...

Alert received upon selecting the React icon button

In the login code below, I have utilized FaEye and FaEyeSlash react icons. However, every time I click on them, a warning message pops up. To avoid this issue, I attempted to switch from using tailwindcss to normal CSS. Login.jsx import { useContext, useS ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...

Long Polling results in the call stack size being exceeded to the maximum limit

I am working on a long polling function that needs to be triggered at a specific time, and then continue as long as the gallery has the updating class. The gallery is represented by $("... "). function pollGallery(gallery){ if (gallery.hasClass("upda ...

Establishing a connection to a remote Mongo database using Node.js

I have a remote MongoDB server and I am looking to establish a connection with it using Node.js. I was able to successfully connect directly with the Mongo shell, but for some reason, I cannot establish a connection to the MongoDB server in Node.js. The co ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

Easily update the title of a webpage in the browser's history using JavaScript

Is it feasible to use JavaScript to modify the title of a page in the browser history even after the page has finished loading? This functionality should work consistently across different browsers, including those that do not support the HTML5 History API ...

Ways to extract all hyperlinks from a website using puppeteer

Is there a way to utilize puppeteer and a for loop to extract all links present in the source code of a website, including javascript file links? I am looking for a solution that goes beyond extracting links within html tags. This is what I have in mind: a ...

Incorporating promises with ajax to enhance functionality in change events

Consider the scenario where you trigger an ajax request upon a change event in the following manner: MyClass.prototype.bindChangeEvent = function(){ $(document).on('change', '#elementid', function(){ var $element = $(this); $ ...

Utilizing multiple parameters as variables in Angular's router

Here is an example of how my router configuration will be set up: { path: ':firstVariable', component: FirstComponent }, { path: ':secondVariable', component: Secon ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

Tips on duplicating an object within a React state without using references

In my React application, I have a state that contains several objects. I need to make a copy of the c: "value" field from the initial state before it gets replaced by the input value from e.target.value. The purpose behind this is to ensure that ...

What is the best way to retrieve a specific property from an array of objects in Angular 6 using typescript?

I am currently working on a budgeting application that incorporates an array of expenses with a price property. Each expense is defined within an Expense model in Typescript. While I can easily access the price property using ngFor loop in HTML, I'm c ...

Sending a document to a distant server using a background script in Thunderbird

I am currently working on a Thunderbird extension that has the ability to upload attached files in emails. The process flow of this extension is outlined below: Clicking on the extension icon will display a popup with options to select from: "Read All", " ...