Express.js v ^ 4.17.1上的'req.body'从发布请求中返回'undefined'

时间:2020-10-28 20:02:29

标签: node.js express ejs router

我一直在尝试将某些东西发送到我的shoutbox_endpoint,但是在Express.JS Backend上,该端点是req.body的端点,返回undefined

发布请求

const headers = {
    "SMN-Auth-JWT": " REDACTED "
};

axios.post(this.endpoint_shoutbox, {
    headers: headers,
    data: {
        user: who,
        message: message,
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

后端端点

router.post('/shoutbox-relay', async (req, res) => {
    console.log(req.params); // {} 
    console.log(req.query); // {}
    console.log(req.body); // Undefined   
});

Main.js

const Logger = require("./LogHandler");
const config = require("../Settings/conf.json");
const Path = require("path");
const ExpressJS = require("express");
const Router = require("./RouterHandler");
const bodyParser = require('body-parser');
const app = ExpressJS();

module.exports.start = async (client) => {
    try {
        app.set("view engine", "ejs");
        app.use("/assets", ExpressJS.static(Path.join(__dirname, "../Website/assets")));
        app.use("/socket.io", ExpressJS.static(Path.join(__dirname, "../Website/assets/socket.io")));
        app.set("views", Path.join(__dirname, "../Website/views"));

        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: true }));
        app.disable("x-powered-by");
    
        app.use(function (req, res, next) {
            req.bot = client;
            next();
        });
        app.use("/", Router.index);
        app.use("/about", Router.about);
        app.use("/chat", Router.chat);
        app.use(function (req, res, next) {
            var err = new Error("File Not Found");
            err.status = 404;
            next();
        });

        const Listener = http.listen(config.Website.port, function () {
            Logger.log("Website Handler", "Webserver Started.");
        });
    } catch (err) {
        Logger.error("Website Handler", `Webserver failed to load due to: ${err}`);
    }
};

1 个答案:

答案 0 :(得分:1)

一个观察结果是,客户端JavaScript上的DATA不是JSON字符串化的。我更喜欢提到contentType:'application / json'

这是我的示例,几乎可以在您的配置中很好地工作。

客户端JS:

function saveBankDetails() {
    someDetails =  { bankDetails: {
        someKey1:   "SOME VALUE 1,
        someKey2: "SOME VALUE 2"
     }
    }
    $.ajax({
        url: ("SOME PATH"),
        method: 'POST',
        data: JSON.stringify(someDetails),
        contentType: 'application/json'
    })
    .done(function(data, textStatus, jXhr) {
        console.log(data);
    })
    .fail(function(jXhr) {
        console.log('failure')
        console.log(jXhr)
    });    

}

服务器端代码:

router.post('SOME PATH', async (req,  res) {
    console.log(req.body.bankDetails)
});

输出:

 {
        someKey1:   "SOME VALUE 1,
        someKey2: "SOME VALUE 2"
 }