Слежу за видеолекцией на 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).
name
послеconst { name, type } = req.body;
? - person Anatoly   schedule 25.11.2020body-parser
? - person Anatoly   schedule 25.11.2020Timeline
в Insomnia. - person Anatoly   schedule 25.11.2020Content-Type: application/json
- person Anatoly   schedule 25.11.2020