DEV Community

thisisreen
thisisreen

Posted on

Can I get a help connecting my project to mongodb

I have a problem connecting my component to the database

this is my registration.component.ts file

import { Component } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent {
  constructor(private apiService: ApiService) { }
  username!: string;
  email!:string;
  password!:string;

  submitRegistrationForm() {
    const registrationData = {
      username: this.username,
      email: this.email,
      password: this.password,
    };
    this.apiService.createUser(registrationData).subscribe(response => {
      console.log('User created successfully!');
    }, error => {
      console.log('Error creating user: ', error);
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

registration.component.html file

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap demo</title>
</head>

<body>
  <div class="container py-5 registration-container">
    <h1 class="text-center mb-4">MS Account Registration</h1>
    <div class="row justify-content-center">
      <div class="col-md-6">
          <form (submit)="submitRegistrationForm()">
            <div class="mb-3">
              <label for="username" class="form-label">Username</label>
              <input type="text" id="username" name="username" class="form-control" required [(ngModel)]="username">
            </div>
            <div class="mb-3">
              <label for="email" class="form-label">Email</label>
              <input type="email" id="email" name="email" class="form-control" required [(ngModel)]="email">
            </div>
            <div class="mb-3">
              <label for="password" class="form-label">Password</label>
              <input type="password" id="password" name="password" class="form-control" required [(ngModel)]="password">
            </div>
            <div class="mb-3">
              <label for="confirm-password" class="form-label">Confirm Password</label>
              <input type="password" id="confirm-password" name="confirm-password" class="form-control" required>
            </div>
            <div class="mb-2 form-check">
              <input type="checkbox" id="terms" name="terms" class="form-check-input" required>
              <label for="terms" class="form-check-label">I agree to the terms and conditions</label>
            </div>
            <div class="text-center">
              <button type="submit" class="btn btn-primary">Register</button>
            </div>
          </form>

      </div>
    </div>
  </div>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private API_URL = 'http://localhost:3000';

  constructor(private http: HttpClient) { }

  createUser(userData: any) {
    return this.http.post(`${this.API_URL}/api/users`, userData);
  }
}
Enter fullscreen mode Exit fullscreen mode

server.js file

const mongoose = require('mongoose');
const cors = require('cors');

const app = express();

// Configure middleware
app.use(express.json());
app.use(cors());

// Connect to the database
mongoose.connect('mongodb://localhost:27017/registerdb', { useNewUrlParser: true, useUnifiedTopology: true });


// Define the User schema
const UserSchema = new mongoose.Schema({
  username: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});

const User = mongoose.model('User', UserSchema);

// Define the API routes
app.post('/api/users', async (req, res) => {
  const { username, email, password } = req.body;
  const user = new User({ username, email, password });
  try {
    await user.save();
    res.status(201).json({ message: 'User created successfully!' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal server error' });
  }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Here is the error I'm encountering

Image description

Top comments (0)