Sending Text Input Data from Angular Form to a Restful API

I'm currently working on a project where I need to send data from a reactive form to a REST API running on my local express.js server. The form consists of basic text input fields like name, surname, and email.

When the form data is submitted, it is sent to a service in the Form.Component.ts file as shown below:

  onSubmit(formDirective) 
 {
  this.personservice.senddata(this.personForm.value).subscribe(data=>{
  console.log(data);
  })
 }

The service then handles posting the data to the REST API:

constructor(private http: HttpClient) 
  {
    console.log('init PS')
  }

  getPeople(): Observable<People[]> 
  {
    return this.http
      .get<People[]>(this._peopleURL)
      .map( (data: any) => data.people);
  }

  private _peopleURL = "http://localhost:8080/api/people";

  senddata(data : any) 
  {
  var body = JSON.stringify(data);
         var headers = new Headers();
         headers.append('Content-Type', 'application/json');
         return this.http.post(this._peopleURL, data);
  }

Although the console log displays the correct data, I'm facing an issue where the data is not being posted to the REST API.

I have tried setting up my express.js server as outlined below:

const express = require('express');

const app = express();

const cors = require('cors')

var corsOptions = {
    origin: 'http://localhost:4200',
    optionsSuccessStatus: 200 
  }

  app.use(function (req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.use(cors(corsOptions))

app.listen(8080, () => {
    console.log('Server gestartet');
});


app.route('/api/people').get((req, res) => {
    res.send({
      people: [
      { vorname: 'max', nachname: 'müller', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0b1a0c0b121e16133f18121e1613511c1012">[email protected]</a>', status: 'true', activity: 'Office' }, 
      { vorname: 'jeremy', nachname: 'püringer', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e9f3c3e4eee2eaefade0ecee">[email protected]</a>', status: 'true', activity: 'Office' },
      { vorname: 'peter', nachname: 'schmidt', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7d7e4d6f61787a6463236e65">[email protected]</a>', status: 'false', activity: 'service' }
    ]
    });
  });

app.route('/api/people/:vorname').get((req, res) => {
    const requestedPersonSurname = req.params['vorname'];
    res.send({ vorname: requestedPersonSurname });
  });

app.route('/api/save').get()


  const bodyParser = require('body-parser');
  app.use(bodyParser.json());
  app.route('/api/people').post((req, res) => {
    res.send(201, req.body);
  });

Answer №1

Give this a try!

 sendData(data: any) {
    var body = JSON.stringify(data);
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');;
    return this.http.post(this._peopleURL, data);
  }

It's important to note that we are constructing the HTTPHeaders object by linking together successive set() methods. This approach is necessary because HTTPHeaders is immutable, so its API functions do not alter the original object. Instead, each set call produces a new HTTPHeaders object with the updated value properties.

VIEW DEMO

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

Having trouble establishing a basic websocket connection in NodeJS

I am currently following a tutorial on WebSocket protocol development from this link: . Upon visiting localhost:1337/index.html, I encountered the following error: This localhost page cannot be found. No webpage was found for the web address: http://loc ...

What is the process for activating JavaScript and embedding it into an HTML document?

I am currently utilizing a JavaScript API that contains several functions. How can I incorporate it into an HTML file? One of the functions, "api.ping()", performs well on PowerShell, but I am encountering difficulties with displaying it on an HTML file. ...

Changing jQuery to plain JavaScript in order to show a div element more effectively

I am attempting to toggle a checkbox to display a header or div that is currently hidden. @media screen and (max-width: 639.98px){ #menuPanel{ display: none !important; } } I am encountering an unresolved method error on ready in JQuery, ...

Found a minor syntax problem in an Angular service related to error handling declaration

As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be benefi ...

Tips for accurately defining prop types in next.js when utilizing typescript?

Here is the content of my index.tsx file: import type { NextPage } from "next"; type AppProps = { articles: { userId: number; id: number; title: string; body: string; }; }; con ...

Encountering a Cross-Origin Resource Sharing (CORS) error when attempting to process payments using Node.js

I am trying to process a payment using PayPal SDK. My frontend is built with AngularJS and my backend uses Node.js. In my frontend, I simply make a call to a route on my Node server like this: $http.post('/paypal/pay', cart) I have CORS config ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

What is the best way to completely clear $rootScope when a user signs out of my application?

In my development work, I frequently find myself using $rootScope and $scope within controllers and services. Despite searching through numerous Stack Overflow answers for a solution to clear all $scope and $rootScope values, such as setting $rootScope t ...

Obtain merged types by accessing a particular property within a deeply nested object

My query is reminiscent of a post on Stack Overflow titled Get all value types of a double-nested object in TypeScript However, my specific requirement involves extracting union types from the values of a designated property. const tabsEnum = { IDCardRe ...

What is the best method for extracting information from different websites? I typically utilize the $.post function for this task

Currently conducting a test on a javascript code located on localhost. The script is dependent on receiving data in JSON format from a remote server. Strangely, when I manually access the JSON url, the data loads without issue. However, when using JavaScri ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

Another option to avoid using complicated else if chains

I'm facing a challenge with a function that returns a value known as user_id. It involves multiple conditions that need to be checked. First condition: Verify the service variable Second condition: If not found, retrieve user_id from local storage ...

Unable to establish breakpoints in TypeScript within VS Code

I seem to be facing an issue while trying to set breakpoints in my TypeScript nodejs app using Visual Studio Code. Despite following the guidelines provided on the Visual Studio Code website, I have not been able to achieve success. Below is the content o ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

Meteor: Incorporating New Fields when Creating an Account

Currently, I am experimenting with the Meteor Roles package found at https://github.com/alanning/meteor-roles in order to add a new field to the user model. The user creation process goes smoothly without any issues, however, the 'roles' field t ...

Accessing the OSRM API allows users to determine the distance to the closest emergency station

I am currently working on a typescript project where I need to calculate the distance to the nearest police station and fire station. My approach involves utilizing typescript for this task. Initially, I attempted to use the following URL that I discovere ...

Using React hooks to control the throttle of useLayoutEffect

I am working on a code snippet that uses useLayoutEffect to attach an event listener for window resize events. I want to enhance it by adding a throttle of 1000ms, so that handleCanvasResize is only called once per second. Can anyone advise on the appropr ...

Initially, when fetching data in React, it may return as 'undefined'

I have a function component in React that handles user login. The functionality is such that, based on the username and password entered by the user in the input fields, if the API response is true, it redirects to another page; otherwise, it remains on th ...

Tips for embedding query values within a mongoose query

I have a database in MongoDB that contains an array with company names. I need to remove a specific element from the array based on its position. So, I crafted a query to achieve this. { company: [ {name: "exist"}, {name: "cool"}, {name: "h ...

Display each new array element on a separate line

let team = [['Sara', 'John', 'Kate']] let newTeam = team.map(function(r) { return r; }) outputs [ [ 'Sara', 'John', 'Kate' ] ] Is there a way to modify it so that each value is r ...