【问题标题】:The request value is undefined请求值未定义
【发布时间】:2020-06-26 05:03:22
【问题描述】:

请问有人可以帮我吗?我正在尝试用 node.js 和 express 编写一个 api。当我做一个获取请求时一切正常,但是当我做一个 POST 时它也在工作,但所有的值总是未定义的。我已经在很好的位置包含了中间件正文解析器,但它无论如何都不起作用。这是我的控制器的代码:

const DB_WRAPPER = require("../_helpers/dbHelper");
const db = new DB_WRAPPER();

module.exports = function(app) {
    app.get("/api/articles", async(req, res) => {
        const result = await db.getAll("SELECT * FROM articles");
        res.status(200).send(result);
    });
    
    app.get("/api/articles/:articleId", async(req, res) => {
        const id = req.params.articleId;
        const result = await db.getOne(`SELECT * FROM articles WHERE articleId = "${id}"`);
        res.status(200).send(result);
    });
    
    app.post("/api/articles", async(req, res) => {
        console.log(req)
        const body = req.body;
        console.log(req.body.titel)
        try {
            await db.cmd(`INSERT INTO articles 
            (titel, preis, beschreibung)
        VALUES ('${body.titel}','${body.preis}','${body.beschreibung}')`);
        } catch (e) {
            res.status(500).json({     
                error: e.toString()
            });
        }
        res.status(201).send({
            message: "article succesfully added"
        });
    });
    
    app.delete("/api/articles/:articleId", async(req, res) => {
        const id = req.params.articleId;
        try {
            await db.cmd(`DELETE FROM articles WHERE articleId = "${id}"`);
        } catch (error) {
            res.status(500).json({
                message: "Product doesnt exist"
            });
        }
        res.status(200).send({
            message: "Product Successfully deleted"
        });
    });

}

和 server.js 文件:

  const express = require("express");
    const bodyParser = require("body-parser");
    const cors = require('cors');
    
    const productController = require ('./controllers/productController');
    const port = process.env.PORT || 3000;
    
    const app = express();


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


app.use(cors())

productController(app);


app.listen(port, () => {
    console.log("The server started on: " + port);
});

请问有人可以帮我吗?谢谢

【问题讨论】:

  • 会不会是你打错​​字了?看看这一行:console.log(req.body.titel) - 看起来应该是console.log(req.body.title)
  • 不,不是,title = title in German :) 这不是 req 未定义的问题
  • 啊,谢谢你的澄清
  • 您如何提出请求?您要发送 JSON 吗?你检查过请求内容类型吗?代码在我看来一切都很好,实际上我对其进行了测试,它工作得很好。
  • 是的,我正在通过 POSTMAN 发送 JSON。我真的不知道为什么它不起作用。我过去也曾构建过这样的 API,并且一切正常。我真的不明白:(

标签: node.js rest express body-parser


【解决方案1】:

我认为你需要使用路由来创建不同的端点

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('<b>My</b> first express http server');
});

// 1) Add a route that answers to all request types
app.route('/article')
.get(function(req, res) {
    res.send('Get the article');
})
.post(function(req, res) {
    res.send('Add an article');
})
.put(function(req, res) {
    res.send('Update the article');
});

// 2) Use a wildcard for a route
// answers to : theANYman, thebatman, thesuperman
app.get('/the*man', function(req, res) {
    res.send('the*man');
});

// 3) Use regular expressions in routes
// responds to : batmobile, batwing, batcave, batarang
app.get(/bat/, function(req, res) {
    res.send('/bat/');
});

app.use(function(req, res, next) {
    res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000.');
});

在这里您可以找到更多示例Express Samples

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2023-04-03
    相关资源
    最近更新 更多