Экспресс-запрос POST с Insomnia — req.body возвращает {}

Слежу за видеолекцией на Express & pg. Я кодирую вместе, поэтому весь код является точной копией из видео-лекции. Я пытаюсь сделать запрос POST, чтобы вставить нового пользователя в мою таблицу пользователей с помощью Insomnia (я также пытался использовать расширение chrome RESTED), но продолжаю сталкиваться с ошибкой:

{
  "error": {
    "message": "null value in column \"name\" violates not-null constraint",
    "status": 500
  }
}

Однако мой запрос выглядит так:

{
  "name": "Jellybean",
  "type": "admin"
}

Я разговаривал с Т.А. и он использовал тот же код, что и я, но он не получил ошибки. Мы говорили около 30 минут, и в конце концов он сказал, что не может понять, в чем проблема, потому что мой код работает нормально на его стороне, и он использует то же тело запроса, что и я. Я думал, что это может быть проблема с Insomnia, но та же проблема возникает, когда я использую расширение RESTED для Chrome. Любая помощь будет принята с благодарностью.

Вот мои пользователи.js (маршруты):

/** Routes for users of pg-intro-demo. */

const express = require("express");
const ExpressError = require("../expressError");
const router = express.Router();
const db = require("../db");

router.get("/", async (req, res, next) => {
    try {
        console.log(req);
        const results = await db.query(`SELECT * FROM users`);
        return res.json({ users: results.rows });
    } catch (e) {
        return next(e);
    }
});

router.get("/search", async (req, res, next) => {
    try {
        const type = req.query.type;
        const results = await db.query(`SELECT * FROM users WHERE type=$1`, [type]);
        return res.json(results.rows);
    } catch (e) {
        return next(e);
    }
});

router.post("/", async (req, res, next) => {
    try {
        const { name, type } = req.body;
        const results = await db.query(
            "INSERT INTO users (name, type) VALUES ($1, $2) RETURNING id, name, type",
            [name, type]
        );
        return res.json(results.rows);
    } catch (e) {
        return next(e);
    }
});

module.exports = router;

Вот мой app.js:

const express = require("express");
const app = express();
const ExpressError = require("./expressError");

// Parse request bodies for JSON
app.use(express.json());

const uRoutes = require("./routes/users");
app.use("/users", uRoutes);

/** 404 handler */

app.use(function (req, res, next) {
    const err = new ExpressError("Not Found", 404);

    // pass err to the next middleware
    return next(err);
});

/** general error handler */

app.use(function (err, req, res, next) {
    // the default status is 500 Internal Server Error
    let status = err.status || 500;

    // set the status and alert the user
    return res.status(status).json({
        error: {
            message: err.message,
            status: status,
        },
    });
});

module.exports = app;

Вот мой db.js:

const { Client } = require("pg");

let DB_URI;

// If we're running in test "mode", use our test db
// Make sure to create both databases!
if (process.env.NODE_ENV === "test") {
  DB_URI = "postgresql:///usersdb_test";
} else {
  DB_URI = "postgresql:///usersdb";
}

let db = new Client({
  connectionString: DB_URI
});

db.connect();

module.exports = db;

Вот мой data.sql (создает таблицу и начальные данные):

CREATE DATABASE usersdb;

\c usersdb;

DROP TABLE IF EXISTS users;

CREATE TABLE users
(
  id SERIAL PRIMARY KEY,
  name text NOT NULL,
  type text NOT NULL
);

INSERT INTO users
  (name, type)
VALUES
  ('Juanita', 'admin');

INSERT INTO users
  (name, type)
VALUES
  ('Jenny', 'staff');

INSERT INTO users
  (name, type)
VALUES
  ('Jeff', 'user');

INSERT INTO users
  (name, type)
VALUES
  ('Jasmine', 'user');

INSERT INTO users
  (name, type)
VALUES
  ('James', 'staff');

INSERT INTO users
  (name, type)
VALUES
  ('Jaimee', 'admin');

Вот мой server.js:

// RUN THIS FILE TO START THE SERVER, NOT APP.JS!
const app = require('./app');

app.listen(3000, function () {
  console.log("Server started on 3000");
});

Вот мой package.json:

{
    "name": "pg-intro",
    "version": "1.0.0",
    "description": "",
    "main": "app.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "express": "^4.17.1",
        "pg": "^8.5.1",
        "supertest": "^4.0.2"
    }
}

Маршруты получения работают отлично, но маршрут публикации продолжает выдавать ошибку и печатать {}, когда я использую console.log(req.body).


person shapirobd    schedule 25.11.2020    source источник
comment
Вы проверили name после const { name, type } = req.body;?   -  person Anatoly    schedule 25.11.2020
comment
@ Анатолий да, получилось как undefined   -  person shapirobd    schedule 25.11.2020
comment
Может быть, это что-то с body-parser?   -  person Anatoly    schedule 25.11.2020
comment
@Anatoly Я только что установил body-parser и изменил свой app.js, включив в него: const bodyParser = require(body-parser); app.use(bodyParser.json()); Все еще получаю ту же ошибку   -  person shapirobd    schedule 25.11.2020
comment
проверить заголовки запроса. Можете ли вы добавить их в свой пост?   -  person Anatoly    schedule 25.11.2020
comment
Вы можете добавить все на вкладке Timeline в Insomnia.   -  person Anatoly    schedule 25.11.2020
comment
Вот что выводится, когда я console.log(req.headers): { host: '127.0.0.1:3000', 'user-agent': 'insomnia/2020.4.2', accept: '/', 'длина содержимого': '42' }   -  person shapirobd    schedule 25.11.2020
comment
Хм. Вы выбрали тип тела как JSON? я не вижу Content-Type: application/json   -  person Anatoly    schedule 25.11.2020
comment
@ Анатолий В этом была проблема! Теперь все работает - большое спасибо за помощь.   -  person shapirobd    schedule 25.11.2020
comment
Я обобщил все это в ответе ниже ) Рад, что был полезен!   -  person Anatoly    schedule 26.11.2020


Ответы (1)


Убедитесь, что вы используете body-parser, а также проверьте заголовки запросов, есть они или нет:

Content-Type: application/json

Если вы используете Insomnia, просто выберите тип кузова JSON и все.

person Anatoly    schedule 25.11.2020