简单均值应用程序中的 500 Internal Server Error

500 Internal Server Error in simple Mean application

我正在 Thinkster.io 上做一个简单的 MEAN 堆栈教程,其中涉及创建一个简单的新闻应用程序。当我尝试 post 一个新项目到服务器时,我得到这个错误,POST http://localhost:3000/posts 500 (Internal Server Error)。它非常模糊,我不知道如何调试它。在 chrome 中,我只能将错误追溯到该方法。

//method in service
o.create = function(post) {
        return $http.post('/posts', post).success(function(data) {
            o.posts.push(data);
    });
};  

//usage
$scope.addPost = function(){
        if(!$scope.title || $scope.title === ""){
            return;
        }
        posts.create({
            title: $scope.title,
            link: $scope.link,
            upvotes : 0,
            comments: [
            {author: "Joe", body: "Class!!", upvotes: 0},
            {author: "Coco", body: "Woof Woof!!", upvotes: 0}
            ]
            })
        $scope.title = "";
        $scope.link = "";
};   

但是问题明显出在后端。即使您不愿意筛选代码,请概述我如何自己调试它。这是我的仓库的 link。 Link to Github

Chrome 输出

XHR finished loading: GET "http://localhost:3000/posts". angular.js:9818
POST http://localhost:3000/posts 500 (Internal Server Error) angular.js:9818
XHR finished loading: POST "http://localhost:3000/posts". angular.js:9818

命令输出

Post 模型上的评论字段需要一个评论 ID 数组。您正在尝试在 create Post 路由中创建评论。您应该按原样保存 post,然后在事后添加注释。或者先创建评论,然后将一个Id数组传递给评论字段。

var mongoose = require('mongoose');

var CommentSchema = new mongoose.Schema({
  body: String,
  author: String,
  upvotes: {type: Number, default: 0}
});

CommentSchema.methods.upvote = function(cb) {
    this.upvotes += 1;
    this.save(cb);
}

mongoose.model('Comment', CommentSchema);

我必须 add/update Comments.js 文件。

user.js

如果您使用此代码进行注册

const express = require("express");
const bcrypt = require('bcrypt')

const router = express.Router();
const User = require("../models/user")

router.post("/register", (req, res, next) =>{
    bcrypt.hash(req.body.password, 10)
    .then(hash =>{
        const user = new User({
            email: req.body.email,
            password: hash
        });
        user.save()
        .then(result => {
            res.status(201).json({
                message: "User created!",
                result: result
            })
        })
        .catch(err =>{
            res.status(500).json({
                err:err 
            })
        })
    })
});
module.exports = router;

*和angular 文件认证-service.ts *

因此在注册时,当您使用相同的邮件注册时会出现此错误 好的

   import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { AuthData } from "./auth-data.model";

@Injectable({providedIn: "root"})

export class AuthService{
    constructor(private http: HttpClient ) {}

    createUser(email: string, password: string ){
        const authData: AuthData =  { email: email, password: password };
        this.http.post("http://localhost:3000/api/user/register", authData)
        .subscribe(Response =>{
            console.log(Response);
        })
    }
}