Cannot get my routes that have been defined - javascript

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.

Related

Serve Vue,.js Pages with Express post with parameters

I've an web application that can render sites embeded. The problem is that this site only send POST requests.
So i thought about serving it using express, then i searched a little here i got the following code to serve it, listening to all GET requests as vuetify pages:
const express = require('express');
const path = require('path');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(__dirname, '/dist/index.html');
});
app.listen(port, hostname, () => {
console.log("Listening at http://%s:%s/", hostname, port);
});
Then I thought to add a post method to, receiving the parameters the page sends:
const express = require('express');
const path = require('path');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(__dirname, '/dist/index.html');
});
app.get('*', (req, res) => {
res.sendFile(__dirname, '/dist/index.html');
});
app.post('/data', (req, res) => {
const id = req.body.id;
res.sendFile(__dirname, '/dist/index.html');
});
app.listen(port, hostname, () => {
console.log("Listening at http://%s:%s/", hostname, port);
});
How do i pass this argument to vue?
Is this the best way to serve vue with a post request?
You are only sending the index.html file, there are other important files generated by vue.js.
In the following file I have a working middleware to serve a vue application which is built in ../../../frontend/dist/.
https://github.com/marekvospel/libregifts/blob/next/apps/backend/src/router/index.ts
The only important thing is the 2 middleware functions. You can replace the '/api' condition with a method check.
if (req.originalUrl.startsWith('/api')) next()

no such file or directory, stat 'C:\idora-photobok\backend\frontend\build\index.html'

So, I got this error while try to ready my application for production. So, my index.js code is
const app = express();
const port = 8000;
const cors = require('cors');
const db=require('./config/mongoose');
const path = require('path')
//library used
const passport = require('passport');
const passportJWT = require('./config/passport-jwt-strategy');
const bcrypt = require('bcrypt');
//middleware
app.use(express.json());
app.use(cors());
//use routes
app.use('/', require('./routes'));
app.use(express.static(path.join(__dirname, '/frontend/build')))
app.get('*', (req, res) =>
res.sendFile(path.join(__dirname, 'frontend', 'build', 'index.html')))
app.listen(port, async function(err){
if(err){
console.log(`error in running of server;${err}`);
}
console.log(`server is running on port:${port}`);
});
This is my file structure. So, If someone know, why this is happening. please reply.
Thanks

How am I supposed to use app.METHOD in Node.js?

so I'm trying to make a simple "route system", that would handle requests and send them to a certain controller.
The problem is that I can't even handle any route, because I get
Cannot GET /
error in response.
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
const express = require('express')
const app = express()
// Route config
const routes = {
['/']: {
controller: 'index',
method: 'get'
},
}
// Load routes
const load = () => {
for (const route in routes) {
app[routes[route].method](route, (req, res) => {
// Do something
})
}
}
exports.load = load
You don't use your router file in app.js, try that:
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
app.use('/', router);
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) { res.send({ success: true }); });
module.exports = router;
It's useless and unreadeable create an array whit your all your routes.
My suggestion is to try use command by terminal express my_app for generate the base structure and try to use it or at least read for see how it's work.
You seem to be lacking the context for how the routing system works within Express.
As a starting point, please create a project with the below structure, and try creating your own route to ensure you have a grasp on how to utilize them properly.
Create a new project folder
cd into the project folder from within your terminal
run npm init -y
Run npm i express dotenv
Create a file named app.js in the root of your project folder and place the below code inside of it:
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json({limit: '30mb', extended: true}));
app.use(express.urlencoded({ extended: true }));
app.listen(process.env.PORT || 3000, () => {console.log('Server successfully started')});
app.get('/', (req, res) => {
return res.send('Hello, World!');
});
Create a new folder named routes
Create a new file named test.js and place it inside of the routes folder
Place the below code in the test.js file.
const router = require('express').Router();
router.get('/', (req, res) => {
return res.send('Hello from your custom route!');
});
module.exports = router;
Go back into your app.js file and add the below lines of code to the bottom of the file
const testRoute = require('./routes/test');
app.use('/test', testRoute);
In your terminal, run node app.js
Make a GET request to http://localhost:3000/test by navigating to it with your browser, or by using a REST client, such as Postman.
Once you have completed these steps, you should understand the basic concept of Express routing.
You can use the router combined with Express Middleware to re-route your user to the proper controller based on the endpoint they are trying to access / the data they are trying to send.
Please test with this code
const express = require('express')
const app = express();
app.get('/', (req, res) => {
res.json({"message": "Welcome! it's working"});
});
The complete code is here on Github

how to solve Express.js 404 status?

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

Api : Express : throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

I have just started with api building using express but getting below error.
below is my code. please help.
Server.js code
const express = require('express');
const mongoose = require('mongoose')
const users = require('./routes/api/users');
const profile = require('./routes/api/profile');
const posts = require('./routes/api/posts');
const app = express();
//DB config
const db = require('./config/keys').mongoURI;
//connet to MongoDB
mongoose
.connect(db)
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
app.get('/', (req, res) => res.send('Hello Ajas Bakran'));
//Use Routes
app.use('/api/users', users);
app.use('/api/profile', profile);
app.use('/api/posts', posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
users.js code
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({msg:'Hello Users'}));
module.exports = router;
profile.js code
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({msg:'Hello profile'}));
module.exports = router;
posts.js
const express = require('express');
const router = express.Router();
router.get('/test', (req, res) => res.json({msg:'Hello posts'}));
module.exports = router;
I refered few answers on stackoverflow, but moslty solution to that was having module.exports = router; this line at the end. but i do have the line present already still i get the same error. Really not sure what is going wrong
From what I can see I think you need to re-write this portion:
router.route('/')
instead of
router.get
Usually these types of error originate from non properly exported router.

Categories

Resources