Encountering issues in transmitting form data to a Node server from Angular

In my Angular application, I am working on creating a registration page with validation. Once the user fills out the form and submits it, the data is sent to the server and saved in MongoDB.

This is the approach I have taken:

  register_user() {
    const data = this.register_form.getRawValue();

    const formData: FormData = new FormData();

    formData.append('name', data.name);
    formData.append('email', data.email);
    formData.append('password', data.password);
    // formData.append('image', this.image);
    formData.append('gender', 'Male');

    formData.forEach((value, key) => {
      console.log(value);
    });

    this.user_service.create_user(formData).subscribe((res) => {
      console.log(res);
    });
  }

Service

  create_user(data: FormData) {
    return this.http.post(`${environment.BASE_URL}/user/create-user`, data, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
  }

Node Server

// Required Route
const User = require('./Routes/user');

// Using Middleware
app.use(cors());
app.use(
  express.urlencoded({
    extended: true,
  })
);
app.use(express.json());

app.use('/user', User);

app.listen(PORT, () => console.log(`App started on http://localhost:${PORT}`));
router.post('/create-user', async (req, res) => {
  console.log(req.body);
  let { name, email, gender, mobile_no, password } = req.body;

  try {
    if (
      !(name && email && gender && mobile_no && password && password.length > 8)
    ) {
      throw new Error(
        `All fields are required - Name: ${name}, Email: ${email}, Gender: ${gender}, Mobile No: ${mobile_no}. Password length must be greater than 8 characters`
      );
    }
    password = bcrypt.hashSync(password, parseInt(process.env.BCRYPT_SALT));

    // let response = await USER.create({ name, email, gender, mobile_no });
    const token = await jwt.sign(
      { name, email, mobile_no, user_id: response._id },
      process.env.JWT_KEY
    );

    response = response.toObject();
    response['token'] = token;

    res.status(200).json({ err: 0, message: 'User Created', response });
  } catch (error) {
    res.status(404).json({ err: 1, message: error.message, error });
  }
});

However, on the server, the request body is coming through as an empty object {}.

If I try to send a normal JavaScript object, it works fine.

How can I resolve this issue? Do I need to install or import any other modules in app.module.ts for FormData to work properly?

Answer №1

If you want to effortlessly handle FormData data in your backend, consider utilizing multiparty. It offers a convenient way to handle the data sent from the frontend.

const multiparty = require('multiparty');

router.post('/create-user', async (req, res) => {
    const form = new multiparty.Form();

    // Handle formData event
    form.parse(req, (err, fields, files) => {
        let {name, email, gender, mobile_no, password} = fields;
        try {
            if (
                !(name && email && gender && mobile_no && password && password.length > 8)
            ) {
                throw new Error(
                    `All fields are required name: ${name}, email: ${email}, gender: ${gender}, mobileNo: ${mobile_no}. Password length must be greater than 8 characters`
                );
            }
            password = bcrypt.hashSync(password, parseInt(process.env.BCRYPT_SALT));

            // Handling user creation process
            // let response = await USER.create({ name, email, gender, mobile_no });
            const token = await jwt.sign(
                {name, email, mobile_no, user_id: response._id},
                process.env.JWT_KEY
            );

            response = response.toObject();
            response['token'] = token;

            res.status(200).json({err: 0, message: 'User Created', response});
        } catch (error) {
            res.status(404).json({err: 1, message: error.message, error});
        }
    });
});

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

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Setting a dynamic routerLink in Angular 2 based on a component's property-value

Recently, I developed a component with a <a> element and a routerLink property that I intended to set from the template in which the component is used. However, when attempting to do so, I encountered an error message stating 'Cannot read proper ...

The function documents.getElementsById() is hindering the effectiveness of Javascript validation

I'm facing an issue with this code. If I uncomment the specific line, the form bypasses validation and goes directly to the linked page in the action attribute. However, if I keep it commented out, the validation runs smoothly, and the alert box displ ...

dynamically display elements within aframe based on specific conditions

In my aframe scene, there are three icosahedrons, a complex particle system, and a cursor that fuses on objects within the scene. The performance of the scene is affected when the particles are visible because the cursor attempts to fuse with every particl ...

Every time I try to access Heroku, I encounter an issue with Strapi and the H10 error code

Upon opening Heroku and running the command "heroku logs --tail", my app encountered a crash and I can't seem to locate my Strapi application in Heroku. 2020-05-04T19:05:38.602418+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GE ...

What causes an exception to be thrown even after being caught in an async function?

Even if an exception is caught, the remaining code will still run. function problematic(){ //throw new Error('I am an exception') return Promise.reject("I am an exception") } ( async function (){ let msg = await problem ...

How can PrimeNG PIE chart values be displayed by default instead of only on hover over the slice?

front end <td> <div class="p-col-8 ui-toolbar-group-right"> <button pButton type="button" icon="pi pi-search" (click)="populate_charts()"></button> </div> </td> TS-File ...

Unable to access the API within Angular using a web browser

My Angular application is hosted within an ASP.NET Core application on IIS. The API controller of the ASP.NET Core application can be accessed using the HTTP client in Angular as well as in a C# console application. However, I am facing an issue where I c ...

Setting the value for a textbox using Jquery's .val() function works, while .attr() does not have the

//unable to get it working $("#TextBoxID1").attr("value","HI Value Change") //works perfectly fine $("#TextBoxID2").val("HI Value Change") <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type= ...

Iterate through an array of strings within a paragraph tag

In my current situation, I am dealing with an array of strings and would like to iterate through it within a <p> tag if the array is empty. This is what I have so far: <p *ngIf="detailMessageMultilines">{{detailMessageMultilines}}< ...

Standardize date formatting in AngularJS

Retrieve the date in the shared format: {{ dateValue | date:{{dateFormat}} }} The following service is provided: app.service('formatting', function() { var format = new Object(); format.dateFormat = 'medium' var ...

What are some techniques for applying CSS styling directly to a custom element?

Check out this amazing resource from HTML5 Rocks about the process of creating custom elements and styling them. To create a custom element, you can use the following code: var XFoo = document.registerElement('x-foo', { prototype: Object.crea ...

Create your own Angular control - rate stars - with dynamic input values

<div class="rating"> <div style="display: inline-block" *ngFor="let starred of stars; let i = index" (click)="rate(i + (starred ? (value > i + 1 ? 1 : 0) : 1))"> <ng-container *ngIf="starred; else noStar"><mat-icon class=" ...

Identifying a particular pattern in a JavaScript string

What is the best way to check if a JavaScript String includes the pattern: "@aRandomString.temp" I need to verify if the String includes an @ character followed by any string and finally ".temp". Thank you ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

Personalized Authorization AngularFire2 Ionic2

After transitioning my application from Ionic 1 to Ionic 2, I encountered an issue when trying to authenticate with Firebase using AngularFire2. In my original app (Ionic 1), I utilized AngularFire along with custom authentication through Slim Framework. N ...

"Encountering a Type Error while attempting to destructure elements within ReactJS

Issue Upon querying objects from the GraphQl server and logging data, I can see the objects in the console. However, when attempting to destructure it as data: { getPosts : posts }, a type error is returned. Furthermore, trying to use map directly on data ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

Filter and search JSON data using React Native

Recently I have started learning about react-native and I am currently utilizing it for my school assignment. Prior to this, I was working with ionic. My current task involves filtering data that is stored in JSON format. I'm curious to know if react ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...