No request body recieved from api call - node.js

This is my server.js -
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
Router (feedbackRouter.js)-
const express = require("express");
const router = express.Router();
router.post("/feedback", (req, res) => {
const feedbackData = req.body;
try {
console.log(feedbackData);
res.send(feedbackData);
} catch (error) {
res.status(400).send(error);
}
});
module.exports = router;
When I make an API call from the frontend(React) or Postman, the req.body gives me undefined and I don't see the content from the request anywhere.
The API call gives me status code of 200 in Postman.
Any idea what might be wrong here? Thanks in advance.

Add app.use(express.json()) to your Code.
Server.js:
const express = require("express");
const connectDB = require("./api/config/db");
const feedbackRouter = require("./api/routes/feedbackRouter");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json())
connectDB();
app.use(feedbackRouter);
app.listen(PORT, () => {
console.log(`SERVER IS LIVE AT ${PORT}`);
});
About express.json() method and its options:
https://expressjs.com/en/5x/api.html
You didn't use any body-parsers, they use to process the body of an request, documentation:
http://expressjs.com/en/resources/middleware/body-parser.html
Postman Request & Response:

Related

Express app on heroku throws authentication error on POST requests

The app works fine on GET requests. But on a POST request with body an application error occurs. I can't figure out this problem.
My app setup using express is like this:
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config()
const port = process.env.PORT || 5000
const app = express()
app.use(cors())
app.use(express.json())
app.get('/', (req, res) => {
res.send('Express Server Running...✔')
})
app.listen(port, () => {
console.log('Listening to port', port);
})

Postman cannot connecto NodeJS server even if its running?

I wrote this code in my node app
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
//middleware
app.use(cors);
//access req.body
app.use(express.json());
app.get("/", async (req, res) => {
try {
res.json("response from server");
// const allCompanies = await pool.query("SELECT * FROM COMPANIES");
// res.json(allCompanies.rows);
} catch (error) {
console.log(error.message);
}
});
const port = 1337;
app.listen(port, () => {
console.log(`Server is starting on port ${port}`);
});
In my terminal it says its running on 1337 however when i try to connect to postman it leaves me hanging? never had this problem before.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
The problem was that you were not calling the cors function on your app.use middleware.
If you change the code to
app.use(cors());
It should work.
Express Documentation

Cannot GET /api

I have a problem with my post data to the server. Not sure why i get an error for get when i changed my rout to post.
routes/feedback.js
const express = require("express");
const router = express.Router();
const { emailFeedback } = require("../controllers/feedback");
router.post("/feedback", emailFeedback);
module.exports = router;
server.js
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
// import routes
const feedbackRoutes = require("./routes/feedback");
// app
const app = express();
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cors());
// routes
app.use("/api", feedbackRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
I believe the usual syntax for an express post route is as follows:
router.post("/feedback", function(req, res){
//grabbing the request body
console.log(req.body);
console.log(req.bodt);
//posting the request
res.json(req.body);
});
A callback function needs to be passed in and receive those request and response parameters (req, res).

No response from nodejs api

This is my code i tried to send a request through http://localhost:3000/api/post/article using postman but i received cannot get as error.
It's working without using router.get but instead using app.get, so i think the problem is with the router.
This is the server.js file
const http = require("http");
const app = require("./app");
app.set("port", process.env.PORT || 3000);
const server = http.createServer(app);
server.listen(process.env.PORT || 3000);
this is the app file
const express = require("express");
const postRoutes = require("./routes/post");
const app = express();
app.use("api/post", postRoutes);
module.exports = app;
This is the router file
const express = require("express");
const router = express.Router();
const postCtrl = require("../controllers/post");
router.get("/article", postCtrl.specArticle);
module.exports = router;
This is the controller file
module.exports.specArticle = (req, res) => {
res.status(200).json({ message: "working currently" });
};
Change this:
app.use("api/post", postRoutes);
to this:
app.use("/api/post", postRoutes);
As best I know, all paths in your route handlers should start with / (at least I have no idea why you would ever not start them with a /).

Express route returning 404 error

The express route in my node app is returning a 404 error. It works locally but on the production server it returns a 404 error (bear in mind that I changed the AJAX url to the one on my production server before uploading). My code:
server.js:
const path = require('path');
const http = require('http');
const express = require('express');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
index.js:
function checkRoute(){
$.ajax({
url: "http://localhost:8080/active-screens",
type: "POST"
})
.success(function(data){
console.log(data);
});
}
checkRoute();
It was a CORS issue as pointed out by #WejdDAGHFOUS.
I updated my server.js to this:
const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
const publicPath = path.join(__dirname, '/../public');
const port = process.env.PORT || 8080;
var app = express();
var server = http.createServer(app);
app.use(express.static(publicPath));
app.post('/active-screens', cors(), function(req, res) {
res.send('route works!');
});
server.listen(port, () => {
console.log(`Server is up on port ${port}`);
});

Resources