简体   繁体   English

我不断收到 http POST http://localhost:3000/api/authenticate 404(未找到)

[英]I keep getting http POST http://localhost:3000/api/authenticate 404 (Not Found)

am using angular 6 and express when am developing this api on authentcate uri it returning Http failure response for http://localhost:3000/api/authenticate : 404 Not Found am using angular 6 and express when am developing this api on authentcate uri it returning Http failure response for http://localhost:3000/api/authenticate : 404 Not Found

i have tried removing of the responses on my user.controller.js but the problem persisits it seems am missing out some point here and i dont know here it is at first i got an error saaying cant send headers after they are sent and the error was on my user.controller.js on this line else return res.status(404).json(info);我已经尝试删除我的 user.controller.js 上的响应,但问题仍然存在,它似乎在这里遗漏了一些点,我不知道这是起初我收到一个错误,说在发送标头后无法发送标头并且错误在我的 user.controller.js 上,否则返回 res.status(404).json(info);

Here is my user.controller.js这是我的用户。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'])});
         } );

}

Here is my user.service.ts这是我的 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);
  }
}```

Here is my sign-in.components.ts这是我的登录.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;

   });
  }
}```

Here is my environment.ts这是我的环境.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.```

Here is my auth.js这是我的 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;```

Here is my index.js这是我的 index.js

```const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors')
const bodyParser = require('body-parser');
require('./passportConfig');
const passport = require('passport');

dotenv.config();


//connect to mongodb
mongoose.set('useFindAndModify', false); mongoose.set('useUnifiedTopology', true);
mongoose.connect(process.env.DB_CONNECT,{ useNewUrlParser:true} , () =>
console.log('connected to db!')
);

//import routes
const authRoute = require('./routes/auth');

//middleware
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());

//error handler
app.use((err, req, res, next) =>{
    if(err.name =='ValidationError')
    {
        var valErrs = [];
        Object.keys(err.errors).forEach(key => valErrs.push(err.errors[key].message));
        res.status(422).send(valErrs);
        next();
    }
});


//route middleware
app.use('/api',authRoute);



app.listen(3000, () => console.log("server Up and Running"));```

Any Help please on this one please thank you all请对此有任何帮助,谢谢大家

The only thing which is remain is to attach the router which you have define in the auth.js file to your express app like this唯一剩下的就是将您在auth.js文件中定义的路由器附加到您的 express 应用程序,如下所示

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

And to prefix all routes define in the auth.js file you attach it as a middleware which is trigger on route prifix with \api const express = require('express');并为auth.js文件中定义的所有路由添加前缀,您将其附加为中间件,该中间件在路由 prifix 上触发\api const 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);

This will make authentication available on url http://localhost:3000/api/authenticate这将使身份验证在 url http://localhost:3000/api/authenticate

You may also get 404 because of this line in authenticate route (by the way I think this must be a 400 - bad request, not 404, which is making confusion.)由于身份验证路由中的这一行,您也可能会得到 404(顺便说一下,我认为这一定是 400 - 错误请求,而不是 404,这会造成混淆。)

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

So to understand this, can you replace your authenticate route like this, and see what logs in the api console:所以要理解这一点,你能不能像这样替换你的身份验证路由,并查看 api 控制台中的日志:

module.exports.authenticate = (req, res, next ) => {
  console.log("req.body: ", req.body)
  //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 {
        console.log("info: ", info)
        return res.status(400).json(info);
      }
  })(req, res);

Also it the angular component, can you change your onSubmit like this for easy debug:另外它是 angular 组件,您可以像这样更改您的 onSubmit 以便于调试:

be sure your form.value is correct:确保您的 form.value 正确:

  onSubmit(form :NgForm)
  {
    console.log("form.value: ", form.value);

   this.userService.login(form.value).subscribe( 
     res =>{
      this.userService.setToken(res['token']);
      this.router.navigateByUrl('/signup');
   },
   err =>{
     console.log("err: ", err.message)
     this.serverErrorMessages = err.message;

   });
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 发布 http://localhost:3000/api/auth/register 404(未找到) - POST http://localhost:3000/api/auth/register 404 (Not Found) POST http://localhost:3000/api/customers 404(未找到)reactjs nodejs - POST http://localhost:3000/api/customers 404 (Not Found) reactjs nodejs POST http://localhost:3000/api/login 404(未找到) - POST http://localhost:3000/api/login 404 (Not Found) POST http:// localhost:3000/404(未找到) - POST http://localhost:3000/ 404 (Not Found) 为什么我收到 POST http://localhost:3000/upload 404(未找到)? - Why I'm getting a POST http://localhost:3000/upload 404 (Not Found)? POST http://localhost:3000/undefined/post 404(未找到) - POST http://localhost:3000/undefined/post 404 (Not Found) POST http:// localhost:3000 / api / courses / [object%20Object] / units 404(未找到) - POST http://localhost:3000/api/courses/[object%20Object]/units 404 (Not Found) 发布 localhost:3000/api/users 404 未找到 - Post localhost:3000/api/users 404 not found 错误“POST http://localhost:3000/api/auth/createuser(与 /api/auth/login 路径相同)404(未找到)”和“未在 Promise 中捕获:语法错误” - Error "POST http://localhost:3000/api/auth/createuser (same with /api/auth/login path) 404 (Not Found)" & "Uncaught in Promise: Syntax Error" React.js / Firebase 应用程序中的 Axios 错误(404):POST http://localhost:3000/login 404(未找到) - Axios error (404) in React.js / Firebase app: POST http://localhost:3000/login 404 (Not Found)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM