Я новичок в стеке MEAN и слежу за этим онлайн-учебником. В этом уроке я должен соединить бэкэнд с внешним интерфейсом, чтобы зарегистрировать пользователя, но я продолжаю получать эту ошибку в своей консоли:
ОПЦИИ http://localhost:8080/authentication/register 0 ()
Для более подробной информации приведено изображение ошибки:
Error
Вот мой код:
RegisterComponent (внешний интерфейс)
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
form: FormGroup;
constructor(private formBuilder: FormBuilder, private authService: AuthService) {
this.createForm();
}
createForm() {
this.form = this.formBuilder.group({
email: ['', Validators.compose([
Validators.required,
Validators.minLength(5),
Validators.maxLength(50),
this.validateEmail
])],
username: ['', Validators.compose([
Validators.required,
Validators.minLength(3),
Validators.maxLength(15),
this.validateUsername
])],
password: ['', Validators.compose([
Validators.required,
Validators.minLength(8),
Validators.maxLength(35),
this.validatePassword
])],
confirm: ['', Validators.compose([
Validators.required
])],
}, {validator: this.matchingPasswords('password', 'confirm')}
);
}
validateEmail(controls) {
// tslint:disable-next-line:max-line-length
const regExp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
if (regExp.test(controls.value)) {
return null;
} else {
return { 'validateEmail': true};
}
}
validateUsername(controls) {
const regExp = new RegExp(/^[a-zA-Z0-9]+$/);
if (regExp.test(controls.value)) {
return null;
} else {
return { 'validateUsername': true};
}
}
validatePassword(controls) {
const regExp = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[\d])(?=.*?[\W]).{8,35}$/);
if (regExp.test(controls.value)) {
return null;
} else {
return { 'validatePassword': true};
}
}
matchingPasswords(password, confirm) {
return (group: FormGroup) => {
if (group.controls[password].value === group.controls[confirm].value) {
return null;
} else {
return {'matchingPasswords': true};
}
};
}
onRegisterSubmit() {
const user = {
email: this.form.get('email').value,
username: this.form.get('username').value,
password: this.form.get('password').value
};
this.authService.registerUser(user).subscribe(data => {
console.log(data);
});
}
ngOnInit() {
}
}
AuthService (Frontend)
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
domain = 'http://localhost:8080';
constructor(private http: Http) {}
registerUser(user) {
return this.http.post(this.domain + '/authentication/register', user).map(res => res.json());
}
}
Authentication.js (серверная часть)
const User = require('../models/user');
module.exports = (router) => {
router.post('/register', (req, res) => {
if(!req.body.email) {
res.json({ succes: false, message: 'Je moet een email opgeven'});
} else {
if(!req.body.username) {
res.json({ succes: false, message: 'Je moet een gebruikersnaam opgeven'});
} else {
if(!req.body.password) {
res.json({ succes: false, message: 'Je moet een paswoord opgeven'});
}
else {
let user = new User({
email: req.body.email.toLowerCase(),
username: req.body.username.toLowerCase(),
password: req.body.password
});
user.save((err) => {
if(err) {
if(err.code === 11000)
res.json({ succes: false, message: 'Gebruikersnaam of email bestaat al' });
else {
if(err.errors) {
if(err.errors.email) {
res.json({ succes: false, message: err.errors.email.message})
} else {
if(err.errors.username) {
res.json({ succes: false, message: err.errors.username.message})
} else {
if(err.errors.password) {
res.json({ succes: false, message: err.errors.password.message})
} }
}
}
else {
res.json({ succes: false, message: 'Kan gebruiker niet registreren, Error: ', err });
}
}
} else {
res.json({ succes: true, message: 'Gebruiker geregistreerd'})
}
});
}
}
}
});
return router;
};
Index.js (Backend)
const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const config = require('./config/database');
const path = require('path');
const authentication = require('./routes/authentication')(router);
const bodyParser = require('body-parser');
const cors = require('cors');
mongoose.Promise = global.Promise;
mongoose.connect(config.uri, (err) => {
if (err) {
console.log('Could NOT connect to database: ', err);
} else {
console.log('Connected to database: ' + config.db);
}
});
app.use(cors({origin: 'http://localhost:4200'}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../frontend/dist'));
app.use('/authentication', authentication);
app.get('**', (req, res) => {
res.sendFile(path.join(__dirname + '/../frontend/dist/index.html'));
});
app.listen(8080, () => {
console.log('Listening on port 8080');
});
Это были единственные файлы, которые я изменил, следуя инструкции. Я использовал cors (в index.js) для подключения внешнего интерфейса к внутреннему, но, похоже, он не работает. Я надеюсь, что вы, ребята, можете мне помочь.