Attempting to imitate a form using Angular 2's HTTP post functionality

I am working on an ionic2 application that requires authentication to be done on an existing PHP website and then execute certain requests within it. I do not have access to the source code of the website. Since I am using ionic2, CORS should not be an issue, and I have manually turned it off in Chrome for testing purposes.

I have created a service that handles the login request to the page at data/login.php. However, I am facing an issue where the login always fails and the _body remains empty.

Additionally, I am unsure how to retrieve and store the session cookie that is set to maintain the session.

Below is the relevant code snippet from the login service:

doLogin(username, password) {

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

    var params = new URLSearchParams();
    params.append('usr', username);
    params.append('psw', password);
    params.append('invia_annuario', 'Accedi');


    this.http.post(this.loginPage, params.toString(), { headers: headers })
        .subscribe(
        data => {

            console.log(data);


        },
        Error => { console.log(Error) },
        () => { console.log("Done") }
        );
}

Here is the structure of a real browser request:

Proper request:

POST /data/login.php HTTP/1.1
Host: [website]
Connection: keep-alive
Content-Length: 55
Cache-Control: max-age=0
Origin: [website]
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.33 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://www.lions.it/data/login.php
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

Request data:

usr=[username]&psw=[password]&invia_annuario=Accedi

Response:

HTTP/1.1 200 OK
Date: Wed, 15 Jun 2016 13:34:24 GMT
Server: Apache
X-Powered-By: PHP/5.5.33
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Refresh: 0; URL=./index.php
Set-Cookie: PHPSESSID=6qp5p3f8tm7bm3hqgttfqk20m1; path=/
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

My custom request looks like this:

POST /data/login.php HTTP/1.1
Host: [website]
Connection: keep-alive
Content-Length: 55
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.33 Safari/537.36
content-type: application/x-www-form-urlencoded
Accept: */*
Referer: http://localhost:8100/?ionicplatform=android
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: PHPSESSID=ua37v7sgojddlnt2d961t5gu33; legatus_post_views_count_22=1

Response:

HTTP/1.1 200 OK
Date: Wed, 15 Jun 2016 13:28:11 GMT
Server: Apache
X-Powered-By: PHP/5.5.33
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Refresh: 0; URL=./index.php
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

How can I correctly send a request to the remote site and obtain the session cookie?

Answer №1

To effectively construct the form data, consider utilizing the set method:

var formData = new URLSearchParams();
formData.set('username', user);
formData.set('password', pass);
formData.set('submit_btn', 'Submit');

For a working example, refer to this plunkr: https://plnkr.co/edit/Xyzabc12JklMnoPqRS3t?p=preview.

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

It is not possible to use an async function with Ionic 4 ToastController buttons

Incorporating a new function into the handler of my ToastController button to return a promise (in this case: this.navCtrl.navigateForward()) is something I need assistance with. This is what my code looks like: const toast = await this.toastController.c ...

Retrieve information from Angular 2 response

In my code, I am working with 1 component and 1 service. Here is the component element : ... constructor(private requestService : RequestService) { } ngOnInit() { this.a = this.requestService.send_request(urlWebAPI); console.log(this.a); } ... ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...

Utilizing the power of Angular 4 in combination with mailgun

I need assistance with setting up an email form on my website using Angular 4 and Mailgun as the mail service. I have a method in my mail service file to send messages, but I keep encountering a Bad Request error stating that 'from' is not presen ...

Tips for integrating CKEditor into an Angular 4 project

To start using CKEditor, I first installed it by running the command npm install ng2-ckeditor. Next, I included ckeditor.js in my index.html file. I then imported { CKEditorModule } from 'ng2-ckeditor'; in my app.module.ts file. After setup, I ...

What is the procedure for linking my SQL database with Angular?

This is a sample HTML code snippet to create a sign-in form: <div class="col-md-8"> <form (submit)="onSubmit()" method="POST"> <input type="text" class="form-control mb-2" name="names" [(ngModel)]="profileForm.name" placeholder="Usern ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Form for creating and updating users with a variety of input options, powered by Angular 2+

As I work on creating a form, I encounter the need to distinguish between two scenarios. If the user selects 'create a user', the password inputs should be displayed. On the other hand, if the user chooses to edit a user, then the password inputs ...

The parameter "path" must be a string type. Instead, we received type undefined. This issue is specific to Ionic 4 on Windows

Encountered an unexpected error that is hindering development on a Windows PC, even though building the app works fine on a Mac. The error message received is: cordova build android --stacktrace config file undefined requested for changes not found at ...

Form control identifier and input field name

I am currently developing a custom input feature for my application. One of the functionalities I want to include is auto-completion, and in my research, I found out that certain conditions need to be met for it to work: In order to enable auto-completi ...

Utilizing checkboxes for toggling the visibility of buttons in Angular

I want to dynamically show or hide buttons based on a checkbox. Here is the HTML code I am using: <input class="form-check-input" [(ngModel)]="switchCase" type="checkbox" id="flexSwitchCheckChecked" (change)=" ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Angular HTTP post is failing on the first attempt but succeeds on the second try

Just started working on my first Angular exercise and encountered an issue where I am receiving an undefined value on the first attempt from an HTTP post request. However, on the second try, I am getting the proper response in Edge and Firefox. Thank you f ...

How do I increase a date by a specific number of days in Ionic 3?

ionViewDidEnter() { let self = this; self.originationsProvider.getOrigination() .then((data) => { self.origination = data; console.log(self.origination, "slefOrigination"); this.complete = self.origination.filter(( ...

Exploring the power of ContentChildren and ViewChildren in AngularElements with Angular 6 - a deep dive into

I have been experimenting with the new AngularElements feature which you can learn more about at https://angular.io/guide/elements. Initially, my tests were successful, but everything came to a halt when I integrated @ContentChildren. It makes sense to me ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Error message "Cannot bind to 'name' because it is not a recognized native property" encountered in Ionic icon configuration

Currently, I am developing a mobile app using Ionic 2 and Angular 2. I encountered an issue when trying to use the [name] property in conjunction with Ionic icons and expressions like this: <icon item-right [name]="result.kind ==='song&apo ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

The ERR_ASSERTION error is thrown because the catch clause variable is not an instance of the Error class

For some reason, I am unable to set up the authentication, firestore, and cloud storage in my project as I keep getting this error message: [error] AssertionError [ERR_ASSERTION]: catch clause variable is not an Error instance at assertIsError (C:\Us ...

Storing the ngFor output in a variable with Angular 2

I've been exploring how to achieve this functionality using AngularJS and was successful with the following code: item in (filteredList.sup = (nozzles | rangeFilter: { flow: calc.q.tempFlow, pressure: calc.pressure } | orderBy: 'pressao')) ...