0

我正在做 API 和微服务项目 - freecodecamp 中的锻炼跟踪器项目

我已经建立了一个在本地运行良好的迷你项目,所以我将它托管在 glitch.com

在那我面临一些错误项目链接请帮我解决这个问题

服务器.js

const express = require("express");
const app = express();
const bodyParser = require("body-parser");

const cors = require("cors");
const { newUser, addExercise, showLogs } = require("./api/index.js");

const mongoose = require("mongoose");

mongoose.connect(process.env.MLAB_URI || "mongodb://localhost/exercise-track");

app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(express.static("public"));
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/views/index.html");
});

app.post("/exercise/new-user", (req, res) => newUser(req, res));
app.post("/exercise/add", (req, res) => addExercise(req, res));
app.get("/exercise/log", (req, res) => showLogs(req, res));

// Not found middleware
app.use((req, res, next) => {
  return next({ status: 404, message: "not found" });
});

// Error Handling middleware
app.use((err, req, res, next) => {
  let errCode, errMessage;

  if (err.errors) {
    // mongoose validation error
    errCode = 400; // bad request
    const keys = Object.keys(err.errors);
    // report the first validation error
    errMessage = err.errors[keys[0]].message;
  } else {
    // generic or custom error
    errCode = err.status || 500;
    errMessage = err.message || "Internal Server Error";
  }
  res
    .status(errCode)
    .type("txt")
    .send(errMessage);
});

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

index.js 文件在这里

const User = require ('../model/user.js');
const Exercise = require ('../model/exercise.js');
const moment = require ('moment');

exports.newUser = function(req, res) {
  let name = req.body.username;
  if (!name) name = 'Mr/Mrs Doe';

  User.findOne({ name: name })
    .then( (user) => {
      if (user) return new Promise( (resolve,reject) => reject('User already exists') );
      else return new User({ name }).save();
    })
    .then( (newUser) => {
      if(!newUser.isNew) res.json({ userId: newUser.userId, name: newUser.name });
    })
    .catch( (error) => res.status(422).json({ error }) );
};


exports.addExercise = function(req, res) {
  // Dates are coming in in this format = 'YYYY-MM-DD';
  let { userId, description, duration, date } = req.body;
  console.log('description:', description, ' - duration: ', duration, ' - date: ', date);
  if (!description) description = 'No description provided';
  if (!duration) duration = '0';
  if (!date) date = moment();

  User.findOne({ userId })
    .then( (user) => {
      if (user) {
        // console.log('---1. Date: ', date);
        const exercise = new Exercise({ description, duration, date });
        exercise.userId.push(user);
        user.exercises.push(exercise);
        return Promise.all([exercise.save(), user.save()]);
      }
      else return new Promise( (resolve,reject) => reject('UserId not found') );
    })
    .then( (exercise) => {
      if(!exercise.isNew) res.json({ userId, description, duration, date: moment(date).format('D MMM, YYYY') });
      else return new Promise( (resolve,reject) => reject('Exercise could not be saved') );
    })
    .catch( (error) => res.status(422).json({ error }) );
};


exports.showLogs = function(req, res) {
  const { userIdLogs, fromDate, toDate } = req.query;
  var populateExercises = (from, to) => {
    let params = {
      path: 'exercises',
      // match: { date : populateExercises(fromDate, toDate) },
      select: 'description duration date',
      options: { sort: { date: -1 }}
    };

    if(from && to) params.match = { date : { $gte: from, $lte: to } };
    else if (from) params.match = { date : { $gte: from } };
    else if (to) params.match = { date : { $lte: to } };
    return params;
  };

  // see if the userId exists
  User.findOne({ userId: userIdLogs })
    .populate( populateExercises(fromDate, toDate) )
    .then( (user) => {
      if (!user) return new Promise( (resolve,reject) => reject('UserId not found') );
      else {
        const { userId, name } = user;
        res.json({
          search: { userId, name, fromDate, toDate },
          total: user.total,
          exercises: user.exercises.map(function(exercise){
            // exercise.bla = moment(exercise.date).format('D MMM, YYYY');
            return {
              _id: exercise._id,
              description: exercise.description,
              duration: exercise.duration,
              date: moment(exercise.date).format('D MMM, YYYY')
            };
          })
        });
      }
    })
    .catch( (error) => res.status(422).json({ error }));
};

错误日志在这里

module.js:478
    throw err;
    ^
Error: Cannot find module '../model/exercise.js'
    at Function.Module._resolveFilename (module.js:476:15)
    at Function.Module._load (module.js:424:25)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/api/index.js:2:18)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/server.js:6:44)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
module.js:478
    throw err;
    ^
Error: Cannot find module '../model/exercise.js'
    at Function.Module._resolveFilename (module.js:476:15)
    at Function.Module._load (module.js:424:25)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/api/index.js:2:18)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
at Object.<anonymous> (/app/server.js:6:44)
    at Module._compile (module.js:577:32)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)

但在我的本地它工作正常,我可以运行我的项目

4

1 回答 1

0

美好的一天,您的文件名似乎是,但execise.js您正在尝试导入exercise. /api/index.js请将文件名编辑mode/execise.jsexercise.js

于 2020-04-19T18:52:18.190 回答