我正在尝试将我的注册组件连接到我的 mongodb 数据库名称 registerdb,集合名称为用户。我的路线似乎有问题,我不确定它
我试过更改端口号并修改我的代码,但仍然连接不成功。
register.component.html代码:
<!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>
注册.component.ts代码
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; // define the property here
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);
});
}
}
server.js代码
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 || 27017;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
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:27017';
constructor(private http: HttpClient) { }
createUser(userData: any) {
return this.http.post(`${this.API_URL}/api/users`, userData);
}
}
这里还有一个错误
不能在同一个端口上同时运行 NodeJS 服务和 MongoDB 服务。您应该将节点的执行端口(例如)设置为 3000,并在 apiservice 中像这样设置 API_URL:
private API_URL = 'http://localhost:3000';
nodejs服务通过27017端口与MongoDB通信