Transmit: Forwarding information back to the recipient

My goal is to send an Http Post request (Registration form) using Angular, have it processed in the API, and if any errors occur like Please enter a username..., I want to return an error message to the client. Below is the Angular code for reference. Thank you!

Angular:

  sendData(data: {username: string, password: string, bdate: Date}){
    let headers = new HttpHeaders({
      'Content-Type': 'application/json', });
  let options = { headers: headers };

    let JsonData:any = JSON.stringify(data);
    console.log(JsonData)
    this.http.post('http://localhost:3000/register', JsonData, options)
    .subscribe((res) => {
      console.log(res)
    })
  }

Answer №1

Retrieve the information from TypeScript

this.http.get<any>('http://localhost:3000/register', options)
.subscribe(response => {
let usernameError = response.usernameError;
})

API:

app.get("/register", (req, res) => {
let dataToSend = {
usernameError: 'Please provide a username!',
}
// transmit the data
res.send(JSON.stringify(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

The error message ``TypeError [ERR_UNKNOWN_FILE_EXTENSION]:`` indicates a

I am encountering an error while trying to run the command ./bitgo-express --port 3080 --env test --bind localhost: (node:367854) ExperimentalWarning: The ESM module loader is experimental. internal/process/esm_loader.js:90 internalBinding('errors ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

.Net Core receives the method name instead of the parameter value passed by TypeScript

Can someone explain why the code is passing "getFullReport" as the eventId instead of the actual value while making its way to the .Net Core 3.1 side? Prior to the call, I double-checked with a console.log to ensure that eventId holds the correct ID I am ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

Using Filepond to upload images in an Express project with EJS integration

Currently, I am working on a project that utilizes express.js for backend functionality and ejs as the rendering template for frontend. As part of this project, I have uploaded some images using filepond which were then converted to base64 format. However, ...

What is the best way to showcase several images using Sweet Alert 2?

In the process of developing my Angular 2 application, I have incorporated sweet alert 2 into certain sections. I am looking to showcase multiple images (a minimum of two) at the same time in the pop-up. Does anyone have any suggestions on how to achieve ...

Angular Bootstrap Modal not Displaying

<img id="1" data-toggle="modal" data-target="#myModal" data-dismiss="modal" src='assets/barrel.jpg' alt='Text dollar code part one.' /> <div id="myModal" class="modal fade" *ngIf="isModalShowing"> <div class=" modal-lg ...

Express: SimpleAuth

I've been attempting to set up basic authorization for the endpoints in my express app using express-basic-auth, but I keep getting a 401 unauthorized error. It seems like the headers I'm sending in Postman might be incorrect: Middleware: app.u ...

Storing a findOneAndUpdate record in Mongoose and MongoDB

I am utilizing mongoose to verify if a user input exists in my database, and if it doesn't, I aim to create a new record with that user input along with a processedInput (handled by a separate function). The code snippet below demonstrates the findOne ...

Navigating in Angular to initiate file retrieval

Is there a way to set up a route in Angular that allows me to download a file? For example, having a route like '/myFile' would result in downloading the file "/assets/files/test.pdf". I've tried using the redirectTo option for routing, bu ...

The combination of using the .share() method with the .subscribe() method is resulting in

I encountered an issue while attempting to utilize share() with subscribe(). Despite starting with subscribe, I received the following error message. How can this be resolved? The main goal is to execute the logic within subscribe. Share is necessary to p ...

verification of information in a file

Consider the following schema: var userSchema = new Schema({ name : String }); var User = mongoose.model('User',userSchema); UPDATE: If a user attempts to update a field that does not exist, I want to throw an exception. How can I ver ...

Utilize Angular 4 to dynamically load templates within a single component

My task is to create a component with multiple HTML templates, each containing at least 20 controls. Depending on certain conditions, a specific template should be loaded. Note: I have opted for 3 different templates because the controls vary based on the ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

I am attempting to retrieve the initial three results from my MySQL database using Node.js, but I keep encountering an error

Below is the code I am currently using: con.query('SELECT * FROM tables', function(err, results) { if (err) throw err console.log(results[0].rawname) for(var i= 0; i <= 3; i++) { ...

Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangel ...

Difficulty Aligning Angular Material Expansion Panel with mat-nav-listI am facing an issue with

Currently, I have implemented a mat-nav-list to showcase the Menu items on my webpage. However, there seems to be an alignment issue with the 4th Menu item which is an Angular Material Expansion control. Refer to the screenshot provided below for clarifica ...

Tips on retrieving a single matching record in a many-to-many relationship using Postgres

In an effort to retrieve a user's pet based on the user's id and the pet's id. Description of my tables: CREATE TABLE pet_owner ( id serial PRIMARY KEY, first_name varchar(100) NOT NULL, last_name varchar(100) NOT NULL, phone_number ...

Angular reloads content when language is switched

I am facing an issue with my language selector and default pipes for number or currency format. Even after changing the language (e.g., from en-US to fr-FR), the thousands separator remains unchanged despite the correct updates in LOCALE_ID and TranslateSe ...

"Error Message: Inconsistent Cookie Values Between Cloud Functions and Express req.headers

Utilizing Firebase Cloud Functions, I am currently working with the cookie module. One function sets the "__session" cookie and then initiates a "GET" request to another function. However, in the second function, when attempting to retrieve the cookie usin ...