简体   繁体   English

[react] 测试 app.post 创建数据库条目时出现错误代码 HTTP/1.1 500 Internal Server Error

[英][react]Getting error code HTTP/1.1 500 Internal Server Error when testing app.post to create a database entry

I am trying to build a website that displays information from a database.我正在尝试建立一个显示数据库信息的网站。 My controller file has the code我的 controller 文件有代码

import express from 'express';
import * as exercises from '../REST API/exercises_model.mjs';

const PORT = 3000;

const app = express();

app.use(express.json());

app.post('/exercises', (req, res) => {
    exercises.createExercise(req.body.name, req.body.reps, req.body.weight, req.body.unit, req.body.unit, req,body.date)
        .then(exercise => {
            res.status(201).json(exercise);
        })
        .catch(error => {
            console.error(error);
            res.status(400).json({ Error: 'Request failed' });
        });
});

app.get('/exercises', (req, res) => {
    let filter = {};
    if(req.query.name !== undefined){
        filter = { name: req.query.name };
       if(req.query.reps !== undefined){
           filter = { reps: req.query.reps};
           if(req.query.weight !== undefined){
               filter = { weight: req.query.weight};
               if(req.query.unit !== undefined){
                    filter = { unit: req.query.unit};
                    if(req.query.date !== undefined){
                        filter = { date: req.query.date};
                    }
               }
           }
       }
    }
    exercises.findExercises(filter, '', 0)
        .then(exercises => {
            res.json({exercises});
        })
        .catch(error => {
            console.error(error);
            res.send({ Error: 'Request failed' });
        });

});

app.put('/exercises/:_id', (req, res) => {
    exercises.replaceExercise(req.params._id, req.body.name, req.body.reps, req.body.weight, req.body.unit, req.body.date)
        .then(numUpdated => {
            if (numUpdated === 1) {
                res.json({ _id: req.params._id, name: req.body.name, reps: req.body.reps, weight: req.body.weight, unit: req.query.unit, date: req.query.date })
            } else {
                res.status(404).json({ Error: 'Resource not found' });
            }
        })
        .catch(error => {
            console.error(error);
            res.status(400).json({ Error: 'Request failed' });
        });
});

app.delete('/exercises/:id', (req, res) => {
    exercises.deleteById(req.params.id)
        .then(deletedCount => {
            if (deletedCount === 1) {
                res.status(204).send();
            } else {
                res.status(404).json({ Error: 'Resource not found' });
            }
        })
        .catch(error => {
            console.error(error);
            res.send({ error: 'Request failed' });
        });
});

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}...`);
});

My model file has the following我的 model 文件具有以下内容

import mongoose from 'mongoose';

mongoose.connect("mongodb://localhost:27017/exercises_db",
    {
        useNewUrlParser: true, useUnifiedTopology: true
    });

const db = mongoose.connection;

db.once("open", () => {
    console.log("Successfully connected")
});

const exerciseSchema = mongoose.Schema({
    name: {type: String, required: true},
    reps: {type: Number, required: true},
    weight: {type: Number, required: true},
    unit: {type: String, required: true},
    date: {type: String, required: true},
});

const Exercise = mongoose.model("Exercise", exerciseSchema);

const createExercise = async (name, reps, weight, unit, date) => {
    const exercise = new Exercise({name, reps, weight, unit, date});
    return exercise.save();
}

const findExercises = async ({}) => {
    const query = Exercise.find(filter)
        .select(projection)
        .limit(limit)
    return query.exec();
}

const replaceExercise = async(_id, name, reps, weight, unit, date) =>{
    const result = await Exercise.replaceOne({_id: _id, name: name, reps: reps, weight: weight, unit: unit, date: date});
    return result.nModifed;
}

const deletebyID = async(_id) => {
    const result = await Exercise.deleteOne({_id: _id});
    return result.deletedCount;
}

export {createExercise, findExercises, replaceExercise, deletebyID };

When testing with测试时

### Create an exercise
POST http://localhost:3000/exercises HTTP/1.1
content-type: application/json

{
    "name": "Squat",
    "reps": 10,
    "weight": 30,
    "unit": "lbs",
    "date": "06-24-21"
}

### Create another exercise
POST http://localhost:3000/exercises HTTP/1.1
content-type: application/json

{
    "name": "Deadlift",
    "reps": 10,
    "weight": 30,
    "unit": "lbs",
    "date": "06-25-21"
}

### Retrieve should return the 2 exercises we just created
GET http://localhost:3000/exercises HTTP/1.1


### Edit the Deadlift. 
### NOTE: Set ID to the ID for Deadlift
PUT http://localhost:3000/exercises/610e523255de4c51c4a3d1db HTTP/1.1
content-type: application/json

{
    "name": "Deadlift",
    "reps": 12,
    "weight": 30,
    "unit": "lbs",
    "date": "06-25-21"
}

### Verify that reps value for Deadlift is now 12
GET http://localhost:3000/exercises HTTP/1.1


### Delete the Deadlift
### NOTE: Set ID to the ID for Deadlift
DELETE http://localhost:3000/exercises/610e523255de4c51c4a3d1db HTTP/1.1

### Verify that the Deadlift exercise has been deleted
GET http://localhost:3000/exercises HTTP/1.1

I receive the following response when testing the first case to create an exercise.在测试第一个案例以创建练习时,我收到以下响应。 I can't test the rest of the cases without at least creating 1 entry.如果没有至少创建 1 个条目,我无法测试案例的 rest。 How can I fix the app.post on the controller or the createExercise function on the model to fix this error and create an entry to continue my testing.如何修复 controller 上的 app.post 或 model 上的 createExercise function 以修复此错误并创建条目以继续我的测试。

HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 1540
Date: Thu, 02 Dec 2021 02:06:53 GMT
Connection: close

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>ReferenceError: body is not defined<br> &nbsp; &nbsp;at file:///D:/Comp%20Sci/CS%20290%20Web%20Development/Assignment%206/REST%20API/exercises_controller.mjs:11:111<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\layer.js:95:5)<br> &nbsp; &nbsp;at next (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\route.js:137:13)<br> &nbsp; &nbsp;at Route.dispatch (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\route.js:112:3)<br> &nbsp; &nbsp;at Layer.handle [as handle_request] (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\layer.js:95:5)<br> &nbsp; &nbsp;at D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\index.js:281:22<br> &nbsp; &nbsp;at Function.process_params (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\index.js:335:12)<br> &nbsp; &nbsp;at next (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\express\lib\router\index.js:275:10)<br> &nbsp; &nbsp;at D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\body-parser\lib\read.js:130:5<br> &nbsp; &nbsp;at invokeCallback (D:\Comp Sci\CS 290 Web Development\Assignment 6\REST API\node_modules\raw-body\index.js:224:16)</pre>
</body>
</html>

Added to the controller file.添加到 controller 文件中。

app.use(express.urlencoded({extended: true}));'''

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

相关问题 React 应用程序返回 500 内部服务器错误 - React app returning 500 Internal Server Error 错误的App.post Node.js - Error App.post Nodejs 使用 React JS 和 Laravel 将带有图像文件的 POST 请求发送到数据库时出现内部服务器错误 - Getting Internal Server Error when sending POST request with an image file to database using React JS and Laravel POST http:// localhost:3000 / upload 500(内部服务器错误) - POST http://localhost:3000/upload 500 (Internal Server Error) $ http.post到php文件,500内部服务器错误 - $http.post to php file, 500 internal server error POST http://localhost:5000/app/auth/login 500(内部服务器错误) - POST http://localhost:5000/app/auth/login 500 (Internal Server Error) 运行OfBiz时出错-HTTP状态500 –内部服务器错误 - Error when Running OfBiz - HTTP Status 500 – Internal Server Error 获取 HTTP 状态 500 ? 将 tomcat 7 升级到 8 时出现内部服务器错误 - Getting HTTP Status 500 ? Internal Server Error while upgrading tomcat 7 to 8 错误 500 Post 方法的内部服务器错误 - Error 500 Internal server error on Post Method 在Express中使用app.post时出错“Pride not defined” - Error 'Pride not defined' when using app.post in Express
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM