简体   繁体   English

带有 Insomnia 的 Express POST 请求 - req.body 返回 {}

[英]Express POST request with Insomnia - req.body returns {}

I'm following a video lecture on Express & pg.我正在关注关于 Express & pg 的视频讲座。 I am coding along, so all of the code is an exact copy from the video lecture.我正在编写代码,所以所有代码都是视频讲座的精确副本。 I am attempting to make a POST request to insert a new user into my users table with Insomnia (I have also tried using the chrome RESTED extension), but keep running into an error saying:我正在尝试发出 POST 请求以将新用户插入到我的用户表中(我也尝试使用 chrome RESTED 扩展),但一直遇到错误提示:

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

However, my request looks like this:但是,我的请求如下所示:

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

I spoke with a TA and he used the same code me, but he did not receive an error.我与一位助教交谈,他使用了与我相同的代码,但他没有收到错误。 We spoke for about 30 minutes and eventually he said he couldn't figure out what the problem was because my code was working fine on his end and he was using the same request body as me.我们谈了大约 30 分钟,最终他说他无法弄清楚问题出在哪里,因为我的代码在他端运行良好,而且他使用的请求正文与我相同。 I thought it might be a problem with Insomnia, but the same problem occurs when I use RESTED chrome extension.我认为这可能是 Insomnia 的问题,但是当我使用 RESTED chrome 扩展时也会出现同样的问题。 Any help would be greatly appreciated.任何帮助将不胜感激。

Here is my users.js (routes):这是我的 users.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;

Here is my app.js:这是我的 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;

Here is my db.js:这是我的 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;

Here is my data.sql (creates the table & starting data):这是我的 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');

Here is my server.js:这是我的 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");
});

Here is my package.json:这是我的 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"
    }
}

The get routes work perfectly fine, but the post route keeps giving me the error and printing {} when I console.log(req.body). get 路由工作得很好,但是当我 console.log(req.body) 时,post 路由一直给我错误并打印 {}。

Make sure you are using body-parser and also check request headers whether they have or not:确保您使用的是body-parser并检查请求标头是否有:

Content-Type: application/json

If you use Insomnia just choose body type JSON and that's it.如果您使用 Insomnia,只需选择体型JSON

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM