API requests are undefined when live, but work on localhost

Issue

I am having trouble with a node.js/express application I am trying to run.
When running on localhost, the data I pass to the route is parsed and I am able to use req.body.message successfully. However on my live site, this only returns undefined. Why is this, and how do I fix it?

This is the node.js app I am using on both the localhost and the live server.

const express = require("express");
const cors = require("cors");
const router = express.Router();
const app = express();

router.post("/send", (req, res) => {
  res.send(`message is ${req.body.message}`);
});

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/", router);
const PORT = 3030;

app.listen(PORT, () => console.log("Server on " + PORT));

If I do a POST with "message":"hello", on my localhost, I get the response with the "message is hello", but on the live server I get "message is undefined".

Any advice appreciated, cheers.

Solution

I solved it. When calling the live api, you need to include a trailing slash.

E.g. examplewebsite.com/send will not work. However, examplewebsite.com/send/ will work.

I don’t know enough about how servers work to explain this, but it solved my problem. I hope anyone else with this issue can benefit from my finding.

Answered By – vespertinial

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published