Express route returning 404 error - node.js

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

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

No request body recieved from api call

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:

Node Express Router can't get response params

I can not retrieve route parameters with a simple express.Router() in an web app.
Here is a minimal example:
var http = require('http');
const express = require('express');
const app = express();
app.use('/hello/:world', express.Router()
.get('/', function (req, res) {
console.log("hello : ", req.params); //
res.status(200).send({status: 'success', params: req.params});
}));
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
I don't get any error, the res.params is simply empty when I try to reach:
http://localhost:3000/hello/100 for example.
Here is the response:
{
"status": "success",
"params": {}
}
What I have tried so far is to set express.Router({ params: 'inherit' })
as told here: https://github.com/expressjs/express/issues/2151#issuecomment-44716623 but it doesn't change anything.
And here is the manual: http://expressjs.com/en/guide/routing.html
Answer:
The thing that finally worked for me, based on these:
API doc :http://expressjs.com/en/api.html
SO example: Express Router undefined params with router.use when split across files
is to set express.Router({mergeParams: true}).
So:
var http = require('http');
const express = require('express');
const app = express();
app.use('/hello/:world', express.Router({mergeParams: true})
.get('/', function (req, res) {
console.log("hello : ", req.params); //
res.status(200).send({status: 'success', params: req.params});
}));
var port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
Is giving the following response over http://localhost:3000/hello/10
{
"status": "success",
"params": {
"world": "10"
}
}

Use of express.static middleware

Both below codes serve index.html at localhost:3000/ when the server is started.
Use of express.static
const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
app.use(express.static(publicPath));
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
Use of app.get
const path = require('path');
const express = require('express');
const PORT = process.env.port || 3000;
const publicPath = path.join(__dirname, '../public');
var app = express();
app.get('/',(req,res) => {
res.sendFile(publicPath + '/index.html');
})
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
So why someone would choose express.static over app.get to serve static html file. What's the use of static middle ware on express
The code that doesn't use express.static will fail when serving any other static page that isn't index.html, even if index.html included other static files(as a css) it would fail.

Resources