Having trouble with Angular 2 not properly sending POST requests?

Having some trouble with a POST request using Angular 2 HTTP? Check out the code snippet below:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import  'rxjs/add/operator/map';    

/** ... */

public sendData(s: string, k: any) {
        let h = new Headers();
        h.append('Content-Type', 'application/json');
        h.append('Accept', 'application/json');

        let content = JSON.stringify({
            username: s,
            key: k
        });
        console.log(content);

        return this.httpService.post(SERVER_URL, content, {
        headers: h
        })
        .map((res: Response) => {
            return res.json();
        });
    }

On the server side, here's the Express code in TypeScript:

public handleWhitelistRequest(req: Request, res: Response) {
    let out: boolean;
    console.log("post request received"); //DEBUG
    if (req.body.key) {
        out = wl.submit(req.body.username, req.body.key);
    } else {
        out = wl.submit(req.body.username, {});
    }

    res.header("Access-Control-Allow-Origin", "*");     
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.json({
        username: req.body.username,
        success: out
    });
}

If you're getting a 'CORS' error message when calling the Angular 2 code to send requests, check the header settings. Also, make sure that the 'post request received' message is logged to the console for debugging purposes.

Some additional details and debug findings:

  • Sending POST requests via Postman to the server works as expected.
  • GET requests are functioning correctly, even when sent from Angular.

It seems like there might be an issue with how the Angular code sends the content. Any insights on this would be greatly appreciated. Thank you!

Answer №1

Give this a shot.

    import { HttpClient, HttpHeaders } from '@angular/common/http';

    constructor(private httpClient: HttpClient) {}


    public sendUserData(username, key) {
       let data = {
           username: username,
           key: key
       };
       return this.httpClient.post(API_URL, data)
       .subscribe((response: any) => {
          console.log(response);
       });
    }

Answer №2

There is no need to include those headers in the request or use JSON.stringify() on the content before sending it.

public sendData(s: string, k: any) {
    let content = {
        username: s,
        key: k
    };

    return this.httpService.post(SERVER_URL, content)
        .map((res: Response) => res.json());
}

Remember, the HTTP method will not execute until you have subscribed to it using subscribe(). It's assumed that you are calling the sendData() method in another component and subscribing to the response.

Keep in mind that the traditional HTTP approach will eventually be phased out in favor of HTTP Client.

If you're interested in learning more about using HTTP Client, check out this resource here

public sendData(s: string, k: any) {
    let content = {
        username: s,
        key: k
    };

    return this.httpService.post<any>(SERVER_URL, content);
}

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

Comparing the distinctions between `findOrCreate()` and `upsert()` in the Sequelize framework

I was browsing through the documentation for Sequelize and came across two methods for doing an upsert: findOrCreate() and upsert(). After reading the descriptions, I'm still unsure about the difference between the two. Specifically, the documentatio ...

Troubleshooting Node.js & Express Application - Periodically Experiencing High CPU Usage

I am currently working on an application using NGinx, Node.js, Express, and Firebase. This app is designed to take input from a mobile app and store it in Firebase, with the option to also upload files to S3. In basic terms, the "create" function of the a ...

Tips on Importing a Javascript Module from an external javascript file into an <script> tag within an HTML file

I'm facing an issue while attempting to import the 'JSZip' module from an external node package called JSZip in my HTML File. The usual method of importing it directly using the import command is not working: <script> import ...

Setting up state using the useState hook in a Typescript environment

At some point in the future, the state will be updated using the useState hook with an array of objects. The interface for this array of objects will look like this: export interface DataSource { dataPiont: Array<DataPoint>; } export interface Dat ...

Having trouble parsing JSON data from Postman into a Mongoose schema due to an invalid format

const Item = mongoose.model('Item',new mongoose.Schema({ title:{ type:String, trim:true, required:true, minlength:1, maxlength:55 }, authorsIds:{ type:[ new mongoose.Schema( ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Guide to removing selected value from a combobox in Angular

I am working on a simple HTML file that consists of one combobox and one clear button. I want the clear button to remove the selected value from the combobox when clicked. Below is my code: mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayou ...

Exploring Improved Methods for Implementing Nested Subscriptions in Typescript

In my Typescript code for Angular 11, I am working with two observables. The first one, getSelfPurchases(), returns data objects containing information like id, user_id, script_id, and pp_id. On the other hand, the second observable, getScriptDetails(32), ...

Issues with Router navigation in an Ionic-Angular application

I am currently working on a straightforward application using Angular 9 and Ionic 5. The main page consists of a list of items. Here is my HTML code: <ion-header> <ion-toolbar> <ion-title>recipes</ion-title> </ion-toolba ...

What is the best way to implement an asynchronous function using a for loop and APIs in Typescript?

Struggling with ensuring my function returns data only after completing all API calls and the for loop. getListingsImages(sessionID, mlsSearchCriteria){ this.http.get(this.laconiaBaseURL + "mls/search/" + sessionID + "?" +querySt ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Using a template reference variable as an @Input property for another component

Version 5.0.1 of Angular In one of my components I have the following template: <div #content>some content</div> <some-component [content]="content"></some-component> I am trying to pass the reference of the #content variable to ...

Utilize Amplify service to send a GET request to an EC2 instance

< I am new to this, so please excuse any misuse of terms. > Hello everyone! I'm currently working on deploying my website. I have uploaded my front-end files to the Amplify app, which has given me an HTTPS URL. My objective is to set up my bac ...

Setting up TypeScript in Node.js

A snippet of the error encountered in the node.js command prompt is as follows: C:\Windows\System32>npm i -g typescript npm ERR! code UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! errno UNABLE_TO_VERIFY_LEAF_SIGNATURE npm ERR! request to https:/ ...

The angular schematic workflow encountered an error while attempting to create a new project

Successfully installed Angular CLI, but I encountered an issue while creating a new project using 'ng new project name'. Some packages were created, but the installation failed with an unexpected end in JSON while parsing near.....'A85qs.... ...

Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below: login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => { this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => { firebase.database().ref(&ap ...

Preact: occasional occurrence of a blank page after refreshing

Starting out with Preact & TypeScript, I decided to kickstart my project using the parcel-preact-typescript-boilerplate. Initially, everything seemed to be working smoothly. However, I noticed that occasionally, especially on reload or initial page lo ...

Creating consistent div sizes for varying image and title lengths in bootstrap

In my angular project, I am receiving data in the form of image, title, and location. Despite my efforts to create a responsive div, I have been unsuccessful in achieving uniform sizes. <div *ngFor="let company of companies" class=" ...

Starting the stored procedure/function using the sequelize.query() method

Below is the stored procedure I have written: CREATE OR REPLACE FUNCTION GetAllEmployee() RETURNS setof "Employees" AS $BODY$ BEGIN RETURN QUERY select * from "Employees"; END; $BODY$ LANGUAGE plpgsql; I am attempting to execute this stored procedure fro ...

Challenges arise when employing reduce with data types in an object

I want to transform an object in a function so that all keys are converted from Camel case to Pascal case. My Declaration: export interface INodeMailerResponseLower { accepted: string[]; rejected: string[]; envelopeTime: number; messageTim ...