愿所有的美好和期待都能如约而至

Express-400发布错误请求并将

发布时间:  来源:互联网  作者:匿名  标签:error Express - 400 bad request on POST and PUT exception express IT资讯 javascrip  热度:37.5℃

本文介绍了Express-400发布错误请求并将的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,因为我是Node.js和Express的新手。我有以下代码,我正在邮递员上测试

const Joi = require('@hapi/joi');
const bodyParser = require('body-parser');

// Load the express framework
const express = require('express');
const app = express();

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

// temp array
const courses = [
    {id: 1, title: 'Learning Node.js'},
    {id: 2, title: 'How to become a full stack dev'},
    {id: 3, title: 'Master your Javascript skills'}
];
app.post('/api/courses', (request, response) => {
    let error = validateCourse(request.body);
    if (error) {
        response.status(400).send(error.details[0].message); // *
        return;
    }

    let course = {
        id: courses.length + 1,
        name: request.body.name
    };

    // TODO save
    console.log('TODO save the record');

    response.send(course);
});

app.put('/api/courses/:id', (request, response) => {
    let course = courses.find(c => c.id === parseInt(request.params.id));
    if(!course) response.status(404).send('Oops!');

    let { error } = validateCourse(request.body);
    if (error) {
        response.status(400).send(error.details[0].message);
        return;
    }

    // TODO save
    console.log('TODO save the record');

    response.send(course);
});


function validateCourse(course) {
    let schema = Joi.object({
        name: Joi.string().min(4).required()
    });
    console.log(course);
    return schema.validate(course);
}

当我发出一个PUT或POST请求时,我提供了一个name(即验证应该通过),我得到了一个400错误。

在POST请求中,我在控制台中看到以下内容,表示我的星号(*)在哪里

TypeError: Cannot read property '0' of undefined
    at /app/index.js:50:48

根据PUT请求,我在控制台中看到以下内容Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

在这两种情况下,我在validate Course函数中的console.log都显示一个空对象{}

这是邮递员的截图

知道我做错了什么吗?

推荐答案

勇敢去编程!

勇敢的热爱编程,未来的你一定会大放异彩,未来的生活一定会因编程更好!

TOP