Я относительно новичок в Angular и начал изучать аутентификацию, и поэтому я пытался настроить аутентификацию для своего собственного приложения Angular.
Регистрация работает и успешно переходит к маршруту, который я предоставляю в случае успеха,Однако вход в систему с правильными учетными данными приводит к ошибке, которую я определил в журнале консоли.
Что именно мне не хватает?
-
Ошибка консоли
Ошибка при входе пользователя: [объект Объект]
-
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const User = require('./models/User')
const Idea = require('./models/Idea');
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/example-app', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', () =>
{
console.log('Connected to MongoDB')
});
// ***************************** \\
// USER REQUESTS
// ***************************** \\
// Post (create) new user
router.route('/register').post((req,res) =>
{
let userData = new User(req.body);
userData.save()
.then(createdUser =>
{
res.status(200).json({'User': 'New user was added successfully'});
})
.catch(err =>
{
res.status(400).send('Failed to create new user');
});
});
// Post (login) existing user
router.route('/login').post((req,res) =>
{
let userData = req.body;
User.findOne({email: userData.email}, (err, foundUser) =>
{
if(err)
{
console.log("Error attempting to login: " + err);
}
else
{
if(!foundUser)
{
res.status(401).send("Email is not registered with us.");
}
else if(foundUser.password !== userData.password)
{
res.status(401).send("Invalid Password");
}
else
{
res.status(200).send('Login Successful');
}
}
});
});
// ***************************** \\
// IDEA REQUESTS
// ***************************** \\
// Get all existing ideas
router.route('/ideas').get((req,res) =>
{
Idea.find((err,foundIdeas) =>
{
if(err)
{
console.log(err);
}
else
{
res.json(foundIdeas);
}
})
});
// Get specific existing idea
router.route('/ideas/:id').get((req,res) =>
{
Idea.findById(req.params.id, (err,foundIdea) =>
{
if(err)
{
console.log(err);
}
else
{
res.json(foundIdea);
}
});
});
// Post (create) new idea
router.route('/ideas/add').post((req,res) =>
{
let ideaData = new Idea(req.body);
ideaData.save()
.then(createdIdea =>
{
res.status(200).json({'idea': 'New idea was added successfully'});
})
.catch(err =>
{
res.status(400).send('Failed to create new record');
});
});
// Post (edit) specific existing idea
router.route('/ideas/update/:id').post((req,res) =>
{
Idea.findById(req.params.id, (err,foundIdea) =>
{
if(!foundIdea)
{
return next(new Error('Could not find or load document'));
}
else
{
foundIdea.title = req.body.title;
foundIdea.textBox1 = req.body.textBox1;
foundIdea.textBox2 = req.body.textBox2;
foundIdea.textBox3 = req.body.textBox3;
foundIdea.textBox4 = req.body.textBox4;
foundIdea.textBox5 = req.body.textBox5;
foundIdea.textBox6 = req.body.textBox6;
foundIdea.save()
.then(foundIdea =>
{
res.json('Idea updated successfully')
})
.catch(err =>
{
res.status(400).send('Failed to update existing record');
});
}
});
});
// Get (delete) specific existing idea
router.route('/ideas/delete/:id').get((req,res) =>
{
Idea.findByIdAndRemove({_id: req.params.id}, (err,foundIdea) =>
{
if(err)
{
res.json(err);
}
else
{
res.json('Delete idea successfully');
}
});
});
app.use('/', router);
app.get('/', (req,res) => res.send('Connected to Server!'));
app.listen(4000, () => console.log("Connected to Express (Port: 4000)"));
-
auth.service.ts [фрагмент]
export class AuthService {
private _uri = 'http://localhost:4000';
private _registerUri = `${this._uri}/register`;
private _loginUri = `${this._uri}/login`;
constructor(private http: HttpClient) { }
// Register new user to database
registerUser(user)
{
return this.http.post<any>(`${this._registerUri}`, user);
}
// Login new user to database
loginUser(email: String, password: String)
{
return this.http.post<any>(`${this._loginUri}`, {email: email, password: password});
}
-
login.component.html
div class="container">
<h1 id="h_Login">Sign Into Your Account</h1>
<div class="row" id="main-content">
<form class="col-8 mx-auto" id="col_FormContent">
<div class="form-group section">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" [(ngModel)]="loginUserData.email" name="email" #email="ngModel">
</div>
<div class="form-group section">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" [(ngModel)]="loginUserData.password" name="password" #password="ngModel">
</div>
<div class="section_Buttons">
<button class="btn btn-m btn-block" type="submit" (click)="loginUser()">Sign In</button>
</div>
</form>
</div>
</div>
-
login.component.ts [фрагмент]
export class LoginComponent implements OnInit {
loginUserData: any = {};
loginForm: FormGroup;
constructor(private authService: AuthService, private router: Router) { }
ngOnInit() {}
// EVENT HANDLER - (Login Button) Verify and Login user from database
loginUser()
{
this.authService.loginUser(this.loginUserData.email, this.loginUserData.password)
.subscribe(
res =>
{
console.log("Login was successful");
this.router.navigate(['/dashboard']);
},
err =>
{
// **** THE ERROR THAT IS RETURNED **** \\
console.log("Error on user login: " + err);
}
);
}
}
-
User.js (схема пользовательской модели на стороне сервера)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let User = new Schema({
email: { type: String },
password: { type: String }
});
module.exports = mongoose.model('User', User);