0

我在 Angular 6 上不断收到此错误,现在在连接注册用户时有代码后端,他应该被定向到管理仪表板不幸的是,当我使用另一条路线时,我正在读取成功的属性为空,弹出窗口告诉我 undefined hellp me 伙计们要在星期三提交这个作业 我是来自坦桑尼亚的新手

core.js:6014 ERROR TypeError: Cannot read property 'success' of null
    at SafeSubscriber._next (login.component.ts:26)

Show 40 more framesHere is my login.components.ts```

这是我的 login.components

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private Auth: AuthService,private router: Router) { }

  ngOnInit() {
  }
  loginUser(event)
  {
    event.preventDefault()
    const target = event.target
    const email= target.querySelector('#email').value
    const password = target.querySelector('#password').value


    this.Auth.loginUser(email, password).subscribe(data => {
      if(data.success)
      {
        //redirect the person to admin page
        this.router.navigate(['admindashboard'])
        this.Auth.setLoggedIn(true)


      }
      else
      {
        window.alert(data.message)
      }
      return false;
    });
    console.log(email, password)
  }

}```

这是我的 auth.service.ts

import { Injectable } from '@angular/core';
import{ HttpClient } from '@angular/common/http';

interface myData
{
  success:boolean,
  message: string
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  uri ='http://localhost:4000';

  private loggedInStatus = false
  constructor(private http: HttpClient) { }

  setLoggedIn(value: boolean)
  {
  this.loggedInStatus = value
  }

  get isLoggedIn()
  {
    return this.loggedInStatus
  }


  loginUser(email,password){
    return this.http.post<myData>(`${this.uri}/register`, {
      email,
      password
    });
  }


}```

这是我的 API

``` server.post('/register', (req, res, next) => {


     const { email, password } = req.body;

     const clearadmin = new Clearadmin({
         email,
         password
     });

     bcrypt.genSalt(10, (err, salt) => {

        bcrypt.hash(clearadmin.password, salt, async (err, hash) => {

            //Hash Password
            clearadmin.password = hash;

            //save clearadmin
            try{
               const newClearadmin = await clearadmin.save();
               res.send(201);
               next();
            }
            catch(err)
            {
             return next(new errors.InternalError(err.message));
            }
        });
     });
    });```

我的 ClearAdmin Mongoose 架构


const ClearAdminSchema = new mongoose.Schema({
    email:
    {
        type:String,
        required:true,
        trim:true
    },
    password:{
        type:String,
        required:true
    }
});

const ClearAdmin = mongoose.model('ClearAdmin', ClearAdminSchema);
module.exports = ClearAdmin;```

    *the new Error am getting n my console now*

    ```Server started on port 4000
    (node:921) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot render headers after they are sent to the client
        at ServerResponse.writeHead (_http_server.js:236:13)
        at ServerResponse.restifyWriteHead [as writeHead] (/Users/retina/ocapp/node_modules/restify/lib/response.js:632:25)
        at flush (/Users/retina/ocapp/node_modules/restify/lib/response.js:849:9)
        at ServerResponse.__send (/Users/retina/ocapp/node_modules/restify/lib/response.js:431:24)
        at ServerResponse.send (/Users/retina/ocapp/node_modules/restify/lib/response.js:316:21)
        at bcrypt.hash (/Users/retina/ocapp/routes/clearadmins.js:42:21)
        at process._tickCallback (internal/process/next_tick.js:68:7)
    (node:921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
    (node:921) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```


4

1 回答 1

1

首先,您没有以正确的方式发送用户凭据,电子邮件和密码应作为服务auth.service.ts中的键值 JSON 对象发送。像这样

loginUser(email,password){
    return this.http.post<myData>(`${this.uri}/register`, {
      email:email,
      password:password
    });
  }

接下来,在您的组件login.component.ts中,您尝试读取成功属性,而在您的 API 中,您的响应不包含此属性。您的 API 响应应如下所示。

res.status(201).json({
                        success:true,
                        msg:'registration successful'
                    })

而且,在您的 API 中,我建议您以这种方式阅读电子邮件和密码

const email = req.body.email;
const password = req.body.password;

替换这个

const clearadmin = new Clearadmin({
         email,
         password
     });

有了这个

const clearadmin = new Clearadmin({
         email:email,
         password:password
     });

将保存方法添加到您的猫鼬模型中,如下所示

const ClearAdminSchema = new mongoose.Schema({
    email:
    {
        type:String,
        required:true,
        trim:true
    },
    password:{
        type:String,
        required:true
    }
});

const ClearAdmin = modules.exports = mongoose.model('ClearAdmin', ClearAdminSchema);
//Save the user
module.exports.saveUser = function(newUser, callback){
    newUser.save(callback);
}

现在,更改您的注册路线

server.post('/register', (req, res, next) => {

     const email = req.body.email;
     const password = req.body.password;

     const clearadmin = new Clearadmin({
         email:email,
         password:password
     });

     bcrypt.genSalt(10, (err, salt) => {

        bcrypt.hash(clearadmin.password, salt, async (err, hash) => {

            //Hash Password
            clearadmin.password = hash;

            //save clearadmin
            Clearadmin.saveUser(clearadmin,(err,registered)=>{
              if(err){
                  res.json({success:false, msg:'Error occurred at backend'})
              }if(registered){
                  res.json({success:true, msg:'user registered'})
              }
            })
        });
     });
    });
于 2019-10-15T07:24:04.277 回答