我有一个带有集成身份验证的基本MEAN应用程序。运行时,没有cli错误,但浏览器控制台显示以下内容:
zone.js:2969 POST http://localhost:4200/auth/signup 404(未找到)
我的app.module.ts
看起来像这样:
mport { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { SlimLoadingBarModule } from 'ng2-slim-loading-bar';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { CreateComponent } from './components/create/create.component';
import { IndexComponent } from './components/index/index.component';
import { EditComponent } from './components/edit/edit.component';
import { AdunitService } from './adunit.service';
import { ShareDetailComponent } from './share-detail/share-detail.component';
import { LoginComponent } from './components/login/login.component';
import { SignupComponent } from './components/signup/signup.component';
const routes: Routes = [
{
path: 'create',
component: CreateComponent
},
{
path: 'edit/:id',
component: EditComponent
},
{
path: 'index',
component: IndexComponent
},
{
path: 'login',
component: LoginComponent,
data: { title: 'Login' }
},
{
path: 'signup',
component: SignupComponent,
data: { title: 'Sign Up' }
}
];
@NgModule({
declarations: [
AppComponent,
CreateComponent,
IndexComponent,
EditComponent,
ShareDetailComponent,
LoginComponent,
SignupComponent,
],
imports: [
BrowserModule,
RouterModule.forRoot(
routes,
{ enableTracing: true }),
SlimLoadingBarModule,
HttpClientModule,
ReactiveFormsModule,
FormsModule
],
providers: [ AdunitService ],
bootstrap: [AppComponent]
})
export class AppModule { }

signup.component.ts
就是这样:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { tap, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
@Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
signupData = { username: '', password: '' };
message = '';
constructor(private http: HttpClient, private router: Router) { }
ngOnInit() {
}
signup() {
this.http.post('/auth/signup', this.signupData).subscribe(resp => {
console.log('signing in', resp);
this.router.navigate(['login']);
}, err => {
console.log('error:', err);
this.message = err.error.msg;
});
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error); // log to console instead
console.log(`${operation} failed: ${error.message}`);
return of(result as T);
};
}
}
&#13;
我的auth.js
文件是这样的:
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/DB');
require('../config/passport')(passport);
var express = require('express');
var jwt = require('jsonwebtoken');
var router = express.Router();
var User = require("../models/user");
var AdUnit = require("../models/AdUnit");
router.post('/signup', function(req, res) {
if (!req.body.username || !req.body.password) {
console.log("Enter username and password.");
res.json({success: false, msg: 'Please pass username and password.'});
} else {
var newUser = new User({
username: req.body.username,
password: req.body.password
});
console.log(newUser);
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
router.post('/signin', function(req, res) {
User.findOne({
username: req.body.username
}, function(err, user) {
if (err) throw err;
if (!user) {
res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.sign(user.toJSON(), config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
module.exports = router;
&#13;
server.js
就是这样:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/DB');
var app = express();
mongoose.Promise = global.Promise;
mongoose.connect(config.DB).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
const adUnitRoutes = require('./routes/adunit.route');
var auth = require('./routes/auth');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use('/login', express.static(path.join(__dirname, 'dist')));
app.use('/signup', express.static(path.join(__dirname, 'dist')));
app.use(passport.initialize());
app.use('/auth', auth);
app.use(bodyParser.json());
// app.use(cors());
const port = process.env.PORT || 4000;
app.use('/adunits', adUnitRoutes);
const server = app.listen(port, function(){
console.log('Listening on port ' + port);
});
&#13;
我不确定为什么找不到注册。