Node.js server running but not loading on browser - javascript

I know this is a simple problem but I have been looking for a solution for the last 2 days and can't seem to find it. I am following a tutorial where we've set up an express server. I think the two relevant files are app.js and auth.js.
APP.js
//PACKAGES
//"mongodb://0.0.0.0:27017/test"
require('dotenv').config()
const mongoose = require('mongoose')
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors')
//LOCAL PACKAGES
const authRoutes = require("./routes/auth")
//CONNECTING TO MONGODB
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true
}).then(() => {
console.log(`DB CONNECTED!!!!!`)
})
//MIDDLEWARE
app.use(bodyParser.json)
app.use(cookieParser())
app.use(cors())
//ROUTES
app.use("/api", authRoutes)
//PORT
const port = process.env.PORT || 8000;
//STARTING A SERVER
app.listen(port, ()=> {
console.log(`app is running at ${port}`)
})
AUTH.js
const express = require('express')
const router = express.Router()
router.get("/signout", (req,res)=> {
res.send("user signout")
})
module.exports = router;
In the console, I see that my server is connected to DB and running on port no 8000
However, when I go to the browser and write http://localhost:8000/api/signout, a spinning wheel that never stops and it does not return my request. I have tried to match the author's code, turn off the firewall, and changed the port number but nothing works. I would be grateful if someone helps as I am stuck on this problem and I want to progress. Thank you!
P.S: my github repo: https://github.com/timothyroybd/ecommerce-website

There is a problem with usage of body-parser.
You have app.use(bodyParser.json)
and should be app.use(bodyParser.json())

Related

Node.js Error: Cannot GET/ from running on the web browser

So here I have 2 route files and 1 controllers for each.
My first router that is root, is working fine !
but my second route that is /teacher is giving me this error "Cannot GET /teacher"
I literally copy pasted the root route code and changed the variable names still its not working.
following are my files:
server.js
const express = require('express');
const dotenv = require('dotenv');
const root_rt = require('./routes/root-rt');
const teacher_rt = require('./routes/teacherlogin-rt')
dotenv.config();
const uri = process.env.DB_URI;
const port = process.env.PORT;
const app = express();
app.use(express.json());
app.get('/', root_rt);
app.get('/teacher', teacher_rt);
app.listen(port, () =>{
console.log(`server started on http://localhost:${port}`);
});
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.route('/')
.get(teacherController.login);
module.exports = router;
teacher-cnt
module.exports.login = function (req, res) {
res.send('this is teacher login page');
};
Thank you in advance.
When using routers, you shouldn't use app.METHOD() to mount them, but app.use():
app.use('/', root_rt);
app.use('/teacher', teacher_rt);
Make the below change in your teacherlogin-rt.js, it will start working
teacherlogin-rt.js
const express = require('express');
const router = express.Router();
const teacherController = require('../controllers/teacher-cnt');
router.get('/', teacherController.login);
module.exports = router;
server.js
app.use('/', root_rt);
app.use('/teacher', teacher_rt);

Heroku url routes can only be reached programmatically

Sorry if this question is vague but I really don't know what code to present.
I have a Heroku webpage which is running fine. I am using reach-router to navigate from one page to another on button clicks: <button onClick={() => navigate('/intro')}>Click</button>. When I do this the url changes appropriately and my content is visible. However if I type in the exact same url I get an error saying Cannot GET /intro. This error even happens if I use the button click to navigate and then reload the page.
It's my understanding that app.use(express.static('build')); will serve my static files.
So why can I visit pages if I start at my root url and navigate from there but I can't enter a url and travel to that page?
The website is live here https://build-a-wedding.herokuapp.com/
Adding more details on my server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const sessionMiddleware = require('./modules/session-middleware');
require('dotenv').config();
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(sessionMiddleware);
app.use(cors());
// Serve static files
app.use(express.static('build'));
app.use(express.static(path.resolve(__dirname, '..', 'build')));
const users = require('./routes/users.router');
const dataFetch = require('./routes/data.router');
const venues = require('./routes/venues.router');
app.use('/users', users);
app.use('/location', dataFetch);
// app.use('/', auth);
app.use('/venues', venues);
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});
When I navigate programmatically here is what i see for my sources
When I type in the same URL here is the source tree
Just create a static.json file at the root of your React project with the following content:
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
This question is possibly duplicated
Make sure that your express app are listening to these routes and sending response to them.
Example:
app.get('/intro', function (req, res) {
res.send(pathToPage);
});

Why does my express router not respond to my get request?

So i have made a simple express app, but i have been trying for several hours to get a response to a simple get request when i visit http://localhost:3000/
This is my app.js
// IMPORTS
const express = require('express')
const mongoose = require('mongoose')
const customerRouter = require('./routes/customerRoute.js')
const app = express()
const PORT = 3000
// CONNECTION
mongoose.connect('mongodb://localhost/Customers', {useUnifiedTopology: true })
mongoose.connection.on('open', () => {console.log('Connected to database.')})
//APP USE ROUTES AND JSON
app.use(express.json)
app.use('/customers',customerRouter)
app.get('/', (req, res) => {
res.send('Home')
})
// APP PORT SET
app.listen(PORT)
console.log('Server started on port 3000')
This is my routes file
const express = require('express')
const router = express.Router()
console.log('into the router')
router.get('/', (req, res) => {
console.log('GET request')
})
module.exports = router
Substitute app.use(express.json) with app.use(express.json()) and everything will work. You have a mistake in this middleware that parses incoming requests with JSON payloads.
Source: express docs
You made a mistake in middleware app.use(express.json()) is a function not a property of the express object.

post request 404 NOT FOUND after hosting website

So I just hosted a website with Network Solutions and when I try to use the contact form on the site, a 404 error appears. I am aware that something is not configured correctly. What do I need to change in my code? I use Node.js and React.
Error: POST http://www.example.com/api/contact 404 (Not Found)
Port 80 doesn't work...
My index.js file:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { contact } = require('./contact');
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.post('/api/contact', contact);
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Do I need to change the PORT code to something else?
I am not aware of how Network Solutions works but the problem is most probably is your port. Check out what is the process.env.PORT (from node console.log) and if it is in 3001 port make sure that port is accessible and not blocked by firewall.

Express body-parser: req.body returns empty object

I've got a simple Express server that uses the body-parser module to access POST-parameters. The app looks like this:
/index.js:
'use strict';
const express = require('express');
const app = express();
const apiRouter = require('./api/routes.js');
// Set our port for the server application
const port = process.env.PORT || 8080;
// Register the routes for the /api prefix
app.use('/api', apiRouter);
// Start server
app.listen(port);
console.log('The server is running on port ' + port);
/api/routes.js:
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Configure app to use bodyParser(). This will let us get the data from a POST
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
// START ROUTES
router.post('/devices', (req, res) => {
console.log(req.body); // Returns {}
res.json(req.body);
});
module.exports = router;
The problem is that the req.body object is empty (Always returns an empty object {}). Since I already loaded the body-parser middleware I have no idea what else I can try. I hope you have any suggestions.
I used the app Postman for testing. It appeared that it sent the POST data as form-data instead of x-www-form-urlencoded. After changing this setting the data showed up.

Categories