others - Javascript - 我不断收到http POST http://localhost:3000/api/authenticate 404 (Not Found)

59 5

我正在使用angular 6,在对uri进行身份验证时,它返回Http错误响应:404 not found

这是我的user.controller.js


const mongoose = require('mongoose');


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


const passport = require('passport');


const _ = require('lodash');



module.exports.register = (req,res, next) => {



 const user = new User();


 user.fullname = req.body.fullname;


 user.email = req.body.email;


 user.College = req.body.College;


 user.Department = req.body.Department;


 user.password = req.body.password;


 user.admintype = req.body.admintype;


 user.save((err, doc) => {


 if(!err) { res.send(doc)}



 else


 {


 if(err.code == 11000)


 res.status(422).send(['Duplicate email Address Found.'])


 else


 return next(err);


 }


 }) 


}



module.exports.authenticate = (req, res, next ) => {


 //calll for passport authentication


 passport.authenticate('local', (err, user, info) => {


 //error form paasport middleware


 if(err) return res.status(400).json(err);


 //registered user


 else if (user) return res.status(200).json({"token":user.generateJwt() });


 //unknown user or wrong password


 else return res.status(404).json(info);


 })(req, res);


}



module.exports.userProfile = (req, res, next) =>{


 User.findOne({ _id:req._id},


 (err,user) =>{


 if(!user)


 return res.status(404).json({ status: false, message : 'User Record not Found. '});


 else


 return res.status(200).json({ status:true , user : _.pick(user, ['fullname','email','university','College','Department','admintype'])});


 } );



}



这是我的user.service.ts


```import { Injectable } from '@angular/core';


import { User } from './user.model';


import{ HttpClient, HttpHeaders } from '@angular/common/http';


import{ environment } from '../../environments/environment';


import { from } from 'rxjs';



@Injectable({


 providedIn: 'root'


})


export class UserService {


 selectedUser: User = {


 fullname:'',


 email:'',


 university:'',


 College:'',


 Department:'',


 password:'',


 admintype:''


 };



 constructor(private http: HttpClient) { }



 postUser(user:User)


 {


 return this.http.post(environment.apiBaseUrl+ '/register' ,user)


 }



 login(authCredentials)


 {


 return this.http.post(environment.apiBaseUrl+ '/authenticate',authCredentials);


 }



 setToken(token:string)


 {


 localStorage.setItem('token',token);


 }


}```



这是我的sign-in.components.ts


```import { Component, OnInit } from '@angular/core';


import { NgForm } from '@angular/forms';


import { UserService } from 'src/app/shared/user.service';


import { Router } from '@angular/router';



@Component({


 selector: 'app-sign-in',


 templateUrl: './sign-in.component.html',


 styleUrls: ['./sign-in.component.css']


})


export class SignInComponent implements OnInit {



 constructor( private userService:UserService, private router:Router) { }



 model = {


 email:'',


 password:''


 };



 emailRegex = /^(([^<>()[].,;: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,}))$/



 serverErrorMessages : string;


 ngOnInit() {


 }



 onSubmit(form :NgForm)


 {


 this.userService.login(form.value).subscribe( 


 res =>{


 this.userService.setToken(res['token']);


 this.router.navigateByUrl('/signup');


 },


 err =>{


 this.serverErrorMessages = err.message;



 });


 }


}```



这是我的environment.ts


```/ This file can be replaced during build by using the `fileReplacements` array.


// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.


// The list of file replacements can be found in `angular.json`.



export const environment = {


 production: false,


 apiBaseUrl:'http://localhost:3000/api'


};



/*


 * For easier debugging in development mode, you can import the following file


 * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.


 *


 * This import should be commented out in production mode because it will have a negative impact


 * on performance if an error is thrown.


 */


// import 'zone.js/dist/zone-error'; // Included with Angular CLI.```



这是我的auth.js


```const router = require('express').Router();


const User = require('../controller/model/User');


const ctrlUser = require('../controller/user.controller');


const jwthelper = require('../jwtHelper')



//validation



router.post('/register', ctrlUser.register);


router.post('/authenticate',ctrlUser.authenticate);


router.get('/userProfile',jwthelper.verifyJwtToken,ctrlUser.userProfile);



module.exports = router;```



时间: 原作者:

150 3

将你在auth.js文件中定义的路由附加到你的应用程序中


const authRouter = require('./auth');



并将所有定义在auth.js文件中的路由作为中间件,apiconst express = require('express') ,


const app = express();



// define all your middleware and all other route



// and here you attach the auth router


app.use('api', authRouter);



在url上提供身份验证 http://localhost:3000/api/authenticate

原作者:
...