0

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.

1
  • 1
    The order of middleware is important in express. While on a cross-origin platform, you need to define your routes after the middleware configurations, or pass required middleware in router.post as a parameter.
    – Sunny
    May 14, 2021 at 4:55

2 Answers 2

0
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Try putting all this middleware before '/send' API end point. Also check console errors that will give you more information about error.

1
  • Rearranging them did not change anything, but thanks May 14, 2021 at 4:54
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.