请求值未定义

时间:2020-06-25 20:17:29

标签: node.js rest express body-parser

请有人可以帮助我吗?我试图用node.js编写一个api并表达。当正在执行一个get请求时,一切都很好,但是当我正在执行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);
});

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

1 个答案:

答案 0 :(得分:0)

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

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