0

I've been trying to get something to send to my shoutbox_endpoint, but on the Express.JS Backend where the endpoint is it returns req.body as undefined

Post Request

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);
});

Backend Endpoint

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}`);
    }
};
Johnty
  • 246
  • 1
  • 2
  • 18
  • Did you use `body-parser`? – Anatoly Oct 28 '20 at 20:03
  • 1
    Smh... are you kidding me... if this is the answer i'm gonna be embarrassed xD – Johnty Oct 28 '20 at 20:05
  • @Anatoly Unfortunately even with body-parser it does the same thing – Johnty Oct 28 '20 at 20:12
  • 1
    Does this answer your question? [Not able to take inputs from HTML form with Node Js](https://stackoverflow.com/questions/64145324/not-able-to-take-inputs-from-html-form-with-node-js) – esqew Oct 28 '20 at 20:12
  • 1
    If it is the case that `body-parser` also didn't help, can you provide the updated script to show how you've used it? – esqew Oct 28 '20 at 20:12
  • @esqew I have provided the main.js file that links to the router I'm using for this `req.body` – Johnty Oct 28 '20 at 20:16

1 Answers1

1

One observation is that, DATA on the client-side JavaScript isn't JSON-stringified. And I would prefer mentioning contentType: 'application/json'

Here is a sample at my end, that's working well with pretty much your configuration.

Client-side 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)
    });    

}

Server-side code:

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

Output:

 {
        someKey1:   "SOME VALUE 1,
        someKey2: "SOME VALUE 2"
 }
Satya Kalluri
  • 5,148
  • 4
  • 28
  • 37