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

Posted

技术标签:

【中文标题】[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 【发布时间】:2022-01-08 14:08:57 【问题描述】:

我正在尝试建立一个显示数据库信息的网站。我的控制器文件有代码

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...`);
);

我的模型文件有以下内容

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 ;

测试时

### 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

在测试第一个案例以创建练习时,我收到以下响应。如果不至少创建 1 个条目,我将无法测试其余的案例。如何修复控制器上的 app.post 或模型上的 createExercise 函数以修复此错误并创建条目以继续我的测试。

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>

【问题讨论】:

您的createExercise() 函数是async,但在返回save() 调用之前您没有使用await @pazitos10 但我不需要使用“new”,因为我正在创建一个条目吗? 您的情况类似于docs 中的示例,在该示例中您定义了名为Exercise 的模型,使用new 创建了一个新模型,但是您在返回之前忘记使用await exercise.save()从那个函数。如果这样做,save() 方法需要一个回调函数作为参数,并将返回 undefined。否则,请使用 async/await 才能使用 Promise。更多关于 save(),here @pazitos10 我注释掉了我的return exercise.save(); 并添加了await exercise.save();,但仍然遇到同样的错误。两者都试过了,也没有任何变化。 您是否在发送响应之前调试了结果以确保对象已被创建? 【参考方案1】:

添加到控制器文件中。

app.use(express.json()) 
app.use(express.urlencoded(extended: true));

【讨论】:

很高兴你成功了。关于express.json()express.urlencoded(),我会将this question 留给未来的读者,这可能会有所帮助。

以上是关于[react] 测试 app.post 创建数据库条目时出现错误代码 HTTP/1.1 500 Internal Server Error的主要内容,如果未能解决你的问题,请参考以下文章

排毒自动化框架指南:React Native?创建 End 2 端和集成测试框架

包含 axios GET 调用的 React-Redux 应用程序测试操作创建者

创建 React App 2 - 删除用于测试的 html 属性

使用 react-testing-library 在 useEffect 中测试 api 调用

如何在单元测试中使用 JSON 发送请求

supertest nodejs 测试获取调用