how to solve Express.js 404 status? - javascript

I'm quite new for node.js and express.js.
I'm trying to create a login form using MERN.
when I try to access register route I always jumping to 404 status I don't understand what's wrong with my code please help me on this. I'm following this youtube tutorial -- https://www.youtube.com/watch?v=y7yFXKsMD_U&t=35s
testing these codes using POSTMAN please refer below screenshot.
[![enter image description here][1]][1]
server.js | File
const express = require("express");
const morgon = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
require("dotenv").config({
path: "./config/config.env",
});
app.use(bodyParser.json());
if (process.env.NODE_ENV === "development") {
app.use(
cors({
origin: process.env.CLIENT_URL
})
);
app.use(morgon("dev"));
}
// Load all routes
const authRouter = require("./routers/auth.route");
// use routes
app.use("/api/", authRouter);
app.use((req, res, next) => {
res.status(404).json({
success: false,
message: "Page Not Founded",
});
});
const PORT = process.env.PORT;
app.listen(PORT, () => {
console.log(`App PORT up on port ${PORT}`);
});
config.env | File
PORT = 5000
NODE_ENV = development
CLIENT_URL = http://localhost:3000
auth.route.js | Route File
const express = require("express");
const router = express.Router();
// Load register Controller
const { registerController } = require("../controller/auth.controller.js");
// register Router path
router.post("register", registerController);
module.exports = router;
auth.controller.js | Controller File
exports.registerController = (req, res) => {
const {name, email, password} = req.body
console.log(name, email, password)
}

In your router path, you need a / in your register route.
router.post("/register", registerController);
You also do not need a trailing slash in your API route.
app.use("/api", authRouter);

Related

Cannot get my routes that have been defined

I am trying to add routes to my expressjs project. I am trying to make it so that when I go to 'localhost:9000/users' it returns 'User List'. Currently it shows ,'Cannot GET /users'. I have tried putting the code in users.js into server.js and replaced the router with app but that did not work.
routes/users.js:
const express = require("express")
const router = express.Router()
router.get("/", (req, res) => {
res.send("User List")
})
router.get("/new", (req, res) => {
res.render("users/new")
})
module.exports = router;
server.js:
const express = require('express')
const app = express()
const port = 9000
const userRouter = require("routes/users")
app.set('view engine', 'ejs')
app.get('/', (req, res) => {
res.render('index', {username: 'xpress'})
})
app.use("/users", userRouter)
app.listen(port, () => {
console.log(`App listening at port ${port}`)
})
I copy your code and only modify
const userRouter = require("routes/users")
to
const userRouter = require("./routes/users")
and I have the desired output
You should use "./" to refer to your files. Otherwise, Node.js will search for package "routes/users" in built-in packages, globally-installed packages, and in node_modules folder. Of course, it doesn't available in these places.

Which part of the Router code provides the TypeError: requires Middleware function but got a Object

In this fictive project I am trying to set up the Routing structure. Although I used module.exports in both files, running a test still gives me the following error:
TypeError: Router.use() requires a middleware function but got a Object
My Code:
Minions.js
const minionsRouter = require('express').Router();
module.exports = minionsRouter;
const {
getAllFromDatabase,
addToDatabase,
getFromDatabaseById,
updateInstanceInDatabase,
deleteFromDatabasebyId,
} = require('./db.js');
minionsRouter.get('/', (req, res, next) => {
const minionsArray = getAllFromDatabase('minions');
if (minionsArray) {
res.status(200).send(minionsArray);
} else {
res.status(404).send();
}
});
API.js
const express = require('express');
const apiRouter = express.Router();
const minionsRouter = require('./minions');
const ideasRouter = require('./ideas');
const meetingsRouter = require('./meetings');
apiRouter.use('/minions', minionsRouter);
apiRouter.use('/ideas', ideasRouter);
apiRouter.use('/meetings', meetingsRouter);
module.exports = apiRouter;
Server.js
const express = require('express');
const app = express();
module.exports = app;
/* Do not change the following line! It is required for testing and allowing
* the frontend application to interact as planned with the api server
*/
const PORT = process.env.PORT || 4001;
// Add middleware for handling CORS requests from index.html
const cors = require('cors');
app.use(cors());
// Add middleware for parsing request bodies here:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// Mount your existing apiRouter below at the '/api' path.
const apiRouter = require('./server/api');
app.use('/api', apiRouter);
// This conditional is here for testing purposes:
if (!module.parent) {
// Add your code to start the server listening at PORT below:
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`)
})
};
Any help is much appreciated!

Error setting cookie and getting a json response with router.post in express, node.js

I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js

req.app.get('db') is undefined when using Massive JS in my Node Application

I am building a Node application using Express, Massive JS, and Postgresql. I was using sequelize but decided to try Massive JS, so I started converting my code to use it.
I have a login endpoint that I'm trying to reach from my Angular 5 app and I am getting an error. This error only occurs on my deployed application. It does work locally without any issues.
Here is the specific error:
TypeError: Cannot read property 'get_user' of undefined<br> at login (/root/firstImpression/server/features/auth/authController.js:7:26)
Here is my folder structure:
+Server
-server.js
+config
-secrets.js
+db
-get_user.sql
+features
+auth
-authController.js
-authRoutes.js
server.js file contents:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const cookieParser = require('cookie-parser');
const secrets = require('./config/secrets');
const massive = require('massive');
// used to create, sign, and verify tokens
var jwt = require('jsonwebtoken');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
//routes
require('./features/auth/authRoutes')(app);
//Connect to database
massive(secrets.development).then(db => {
app.set('db', db);
});
// Angular DIST output folder
app.use(express.static(path.join(__dirname, '../dist')));
//Set up static files
app.use(express.static('../dist'));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
get_user.sql file contents:
SELECT * FROM users WHERE username = $1;
authController.js file contents:
const jwt = require('jsonwebtoken');
const secrets = require('../../config/secrets');
const bcrypt = require('bcrypt');
module.exports = {
login: (req, res) => {
req.app.get('db').get_user(req.body.username).then(user => {
if(user[0]) {
bcrypt.compare(req.body.password, user[0].password,
function(err, result) {
if(result) {
var token = jwt.sign({user}, secrets.tokenSecret,
{expiresIn: '1h'});
res.status(200).json({
token: token,
user: user
})
} else {
res.status(200).json("Invalid username and/or
password.");
}
});
} else {
res.status(200).json("Could not find that user.");
}
})
}
}
authRoutes.js file contents:
var authController = require('./authController');
module.exports = (app) => {
app.post('/user-auth', authController.login);
}
The error is occuring in the authController.js file on this line:
req.app.get('db').get_user(req.body.username)
I've been reading the docs for massive js and learned the importance of keeping the DB folder on the same level where it's initialized, which is my server.js file.
As I stated earlier, when I run this on my local machine, it works great; However as soon as I deploy it to my live environment, I receive the error.
Any help or direction would be greatly appreciated. Let me know if any other information is required, and I will gladly provide it.
Your app setup should probably be wrap like
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
const cookieParser = require('cookie-parser');
const secrets = require('./config/secrets');
const massive = require('massive');
// used to create, sign, and verify tokens
var jwt = require('jsonwebtoken');
//Connect to database
massive(secrets.development).then(db => {
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
app.set('db', db);
// Angular DIST output folder
app.use(express.static(path.join(__dirname, '../dist')));
//routes
require('./features/auth/authRoutes')(app);
//Set up static files
app.use(express.static('../dist'));
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
});

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

Categories

Resources