Can't reach localhost:PORT created in Node.js and express - node.js

require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors);
const connectDB = require('./config/mongoDB');
const PORT = process.env.PORT || 8000;
// body parser
app.use(express.json({ extended: false }));
//router
app.use(
'/',
require('./routes/index')
);
app.listen(PORT, (req, res) => {
connectDB();
console.log('listening on port ' + PORT);
});
so this is my express server code, it was working yesterday but I can't reach localhost: PORT (via postman and browser) today but it is running and listening to PORT. Where it goes wrong?

The cors middleware should be called with parenthesis, as a function:
app.use(cors());
You are setting the body parser middleware incorrectly, change
app.use(express.json({ extended: false }));
to:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Related

Though deprecated, shouldn't body-parser still work?

Though body-parser has been deprecated, it should still work.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express(); //this is a new instance of express
app.use(express.static("public"));
app.use(bodyParser, urlencoded({ extended: true }));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
Console output using body-parser
[app crash error](https://i.stack.imgur.com/fkLVH.png)
And my code with body-parser commented out...
const express = require("express");
//const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express(); //this is a new instance of express
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//app.use(bodyParser, urlencoded({ extended: true }));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
This works and my app doesn't crash
Please refer to the docs on how to use body-parser. https://www.npmjs.com/package/body-parser
app.use(bodyParser.urlencoded({ extended: true }));

Get empty req.body when deployed on Heroku

I have a react app front end posting data to my server(use express) deployed on Heroku. Code works well when both client and server running on localhost, but when it's on Heroku, the req.body always gets empty object {}.
Can anyone point out what's going wrong here? Thanks in advance :)
React code:
axios.post("/api", data, {headers: { "Content-Type": "application/json;charset=utf-8" }})
Express code:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cors({origin: URL,credentials: true}));
app.post("/api", (req, res) => {const data = req.body; console.log(data);};
This run perfectly on my computer. The log and the response works just fine. Hope it helps. I think the problem could be you are sending a GET request instead of a POST request.
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({origin: new URL('http://localhost:3000'), credentials: true})) // Add this 'new' keyword to URL
app.post("/api", (req, res) => {
const data = req.body
console.log(data)
res.send(data) // Added this to allow request to end
})
// Added this part to start the server listen.
const port = process.env.PORT || 3000
app.listen(port , () => {
console.log('Server is running on port '+3000)
})

Request body when POSTing using Node.js and Express is empty or undefined

I have the following Typescript code:
import express = require('express');
const app: express.Application = express();
const port: number = 3000;
app.listen(port, () => {
console.log("Server started on port" + port);
app.use(bodyParser.urlencoded({ extended: true }));
})
app.post('*', (req, res) => {
console.log(req.body);
});
For some reason req.body is always undefined instead of getting the key-value pairs sent via postman. Adding app.use(bodyParser.urlencoded({ extended: true })); only changes the body from undefined to {}.
What could be the issue in this case?
The line app.use(bodyParser.urlencoded({ extended: true })); must be called before app.listen.
If you are using express 3.0 and below use the following code instead as answered here:
const app = express.createServer();
app.use(express.bodyParser());
If still doesn't work make sure in Postman that you are sending the data as application/x-www-form-urlencoded

Vhost + express why doesn't work?

I try to configure my node.js + express application for creation multiple domain server. This is my code, but unfortunately it's not working. Please explain me, what is wrong in this code?
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const vhost = require('vhost')
const app = express();
app.use(bodyParser.json());
// Port
const port = 8081;
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(vhost('*.localhost:8081', function(req, res, next){
res.send('Ok, its work.');
}));
app.listen(port, function(){
console.log('App is running on port '+ port);
});

node Cannot POST /api/register

I'm not sure why I am getting the cannot POST error. I am passing the correct routes. The server is listening on a port.
index.js
const router = require('./router');
var app = express()
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("App now running on port", port);
});
router(app);
router.js
const Authentication = require('./authentication');
const express = require('express');
const passport = require('passport');
const requireAuth = passport.authenticate('jwt', { session: false });
const requireLogin = passport.authenticate('local', { session: false });
module.exports = function(app) {
const apiRoutes = express.Router();
const authRoutes = express.Router();
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/login', requireLogin, Authentication.login);
authRoutes.post('/register', Authentication.register);
app.use('/api', apiRoutes);
};
You're trying to access /api/register, but look at the way you've registered your routers:
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/login', requireLogin, Authentication.login);
authRoutes.post('/register', Authentication.register);
app.use('/api', apiRoutes);
You've made authRoutes a child of apiRoutes, so /register is being served at api/auth/register.
Easy mistake to make when you've got several routers all linked up to each other :)

Resources