简体   繁体   中英

Postman x-www-form-urlencoded returns null value for a POST request even though the input field is filled

I used the postman's raw option and it worked, my input value returned as expected. But when I use the x-form-urlencoded option, "null" is returned. The get request all works well. Find below the screenshot of the postman cross-section:

Postman Snapshot

I manually created the tables and rows with the following postgres scripts:

CREATE TABLE graduates (id SERIAL PRIMARY KEY, name TEXT);

CREATE TABLE offers (id SERIAL PRIMARY KEY, title TEXT, graduate_id INTEGER REFERENCES graduates (id) ON DELETE CASCADE);

INSERT INTO graduates (name) VALUES ('Elie'), ('Michael'), ('Matt'), ('Joel');

INSERT INTO offers (title, graduate_id) VALUES ('Teacher', 1), ('Super Teacher', 2), ('Mathematician', 3), ('Developer', 4), ('Super Doctor 1', 3), ('Super Doctor 2', 4), ('Super Developer 1', 2);

A snippet of my graduates' route for POST request is as follows;

// This route is mounted on /graduates in app.js

router.post("/", async (req, res, next) => {
    try {
        const result = await db.query(
            "INSERT INTO graduates (name) VALUES ($1) RETURNING *", 
            [req.body.name]
        );
        return res.status(201).send(result.rows[0]);
    } catch(err) {
        return next(err);
    }
});

I look forward to an answer. Thanks.

You need a parser to getthe name from request body. Now there's one unbuilt with express. Add these two lines at the top and it will work:

app.use(express.json())
app.use(express.urlencoded({ extended: false }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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