I am learning express js.
Here I am creating a crud project in student data. I have created routes and controllers but when I include it in my main app.js , my router seems not working.
Please guide me.
P.S:I am working on ES6.
My app.js
import express from 'express';
import connectDB from './db/connectdb.js'
import web from "./routes/web.js"
import{join} from 'path'
const app = express();
const port = process.env.PORT || "8080"
const DATABASE_URL ="mongodb://127.0.0.1:27017"
//loading static files
app.use('/student',express.static(join(process.cwd(),"public")))
//loading routes
app.get('/student',web)
//set template engine
app.set("view engine","ejs")
app.listen(port,()=>{
console.log("Server listening at port no:"+port)
})
connectDB(DATABASE_URL)
My router file saved as web.js
import express from 'express';
import StudentController from "../controllers/studentController.js"
const router = express.Router();
router.route('/',StudentController.getAllDoc)
export default router
My studentController.js
class StudentController{
static getAllDoc = (req,res)=>{
res.render('index')
}
}
export default StudentController
I expected my ejs file named as index.ejs to run which is in views folder, but the result is like cannot get /student/
.use is used to register middleware, serve group of route,...
.get, .post is a single route.
Please change your code to something like this:
app.js
//loading static files
app.use(express.static(join(process.cwd(),"public")))
//loading routes
app.use('/student',web)
web.js
const router = express.Router();
router.get('/',StudentController.getAllDoc)
export default router
Related
I was working on a personal express project. I've created two files one server file and other restaurants.route.js to sepearate routes and server code. But I'm not able trigger the home route from local host. Moreover no console error is showing only the 404 page error.
server.js code:
import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";
// initialising express app
const app = express();
// applying middlewears
app.use(cors());
app.use(express.json());
app.use("api/v1/restaurants", restaurants);
app.use("*", (req, res) => res.status(404).json({error: "not found"}));
export default app;
restaurants.route.js:
import express from "express";
// express router
const router = express.Router();
router.route("/")
.get((req, res) => {
res.send("Hello World");
});`enter code here`
export default router;
It looks like you might be missing the leading forward slash (/) in the path you're using to mount the restaurants router in your server.js file. When you use the app.use() method to mount a router, the path you specify should start with a forward slash.
So instead of this:
app.use("api/v1/restaurants", restaurants);
Try this:
app.use("/api/v1/restaurants", restaurants);
I am having a hard time sending css files with express. The way my project is structured is I have a src folder and inside the src folder is the app.js for the express code as well as another folder titled "public". Inside of this public folder I have an experience.html page as well as an experience.css page. I can only get the html to render on the page and cannot get the css styling to show up. Attached is my code for the app.js page.
const express = require('express');
const app = express ();
const port = process.env.Port || 3000;
app.get('/experience', (req, res) => {
res.sendFile(__dirname+'/public/experience.html');
})
app.use(express.static('/public/experience.css'))
app.listen(port);
Just using middleware is enough, you don't need dedicated get routes to the files unless you want to mask some of the filenames.
This should work for your case
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
You can access them on http://localhost:3000/experience.html, http://localhost:3000/experience.css
You can use the Express static middleware with the path to the public folder.
Once you do that, you can expose a route to the files (or) you can access at localhost:9900
//Import modules
const express = require("express");
const path = require("path");
// Define PORT for HTTP Server
const PORT = 9900;
// Initialize Express
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, (err) => {
console.log(`Your dog server is up and running!`);
});
I have set up my code in server.js which worked fine. I am now trying to clean up the server.js code by splitting the code into different routes.
I am using the express.Router to link up the files but i am struggling to understand why my post route is braking.
In the server.js file
// dependencies
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
// routes
constpurchaseOrders = require("./routes/purchaseOrders");
app.use("/purchaseOrders", purchaseOrders);
// listen
app.listen(3000, function(){
console.log("Server started on port 3000");
});
In the purchaseOrders.js file
// dependencies
const express = require("express");
let router = express.Router();
const mongoose = require("Mongoose");
const connection = require("../routes/mongoose.js");
const Po = require("../routes/schemas.js:);
// post route
router.post("/addpo, function(req.res){
//long code lines here
po.save();
res.redirect("/");
});
module.exports = router;
So with this route, i have the following end point on the route.get:
10.0.0.15:3000/purchaseOrders/addpo
Now the problem comes in when i submit the form, it returns "cannot POST /addpo" and the end point shows:
10.0.0.15:3000/addpo
On my ejs file i have set the form up as follows:
<form action="/addpo" method="post">
On the mongoose.js connection i export as follows:
module.exports = mongoose;
On the schemas.js i export:
module.exports = Po;
I know I did something wrong with the routing but i cannot figure our why.
Thanks alot :-)
if you need the /addpo path to work, change this on server.js:
app.use("/", purchaseOrders);
NOT
app.use("/purchaseOrders", purchaseOrders);
Other option
server.js:
app.use("/addpo", purchaseOrders);
purchaseOrders.js
router.post("/", function(req.res){
If you add a route before calling a router it will be added in front of it.
So, yo can use the route action="/addpo" in the html.
Express docs
I am working on Node Koa2 API. I am performing CRUD operations with Mongoose. When I am working with only one file ("app.js") its working fine. But when I am separating it into controllers, routes and model, it is showing following error: TypeError: route.routes is not a function in the app.js file. Thanks in Advance for the help.
Error Description:
import Koa from 'koa';
const BodyParser = require("koa-bodyparser");
const logger = require('koa-logger');
import router from './routes/index';
require('mongoose');
require('./config.js');
const app = new Koa();
// Use the bodyparser middlware
app.use(BodyParser());
app.use(logger());
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3001, () =>{
console.log('Server is running on port: 3001');
})
export default app;
wellcome to SO, change the fallowing in your code:
app.use(router.routes()) //replace for
app.use('/', router)
Hope it fixes the problem.
As per your issue for e.g. your index file path is (./routes/index).Then the code in app.js as follows:-
var index = require('./routes/index');
app.use('/',index);
Here is a picture of my project directory.
I have my logo in the template/assets/logo.png.
In my server.ts file, I use middleware express as app.use( express.static( "template" ) );
unfortunately, When I try to display the logo in my html file, it doesn't display.
<img src="assets/logo.png" alt="Logo">
Here is my server.ts file:
// Import everything from express and assign it to the express variable
import express from 'express';
import fs from 'fs';
// Import WelcomeController from controllers entry point
import {WelcomeController} from './app/controllers';
// Create a new express application instance
const app: express.Application = express();
// The port the express app will listen on
const port: any = process.env.PORT || 3000;
// Template folder
app.use( express.static( "template" ) );
// Mount the WelcomeController at the /welcome route
app.use('/', WelcomeController);
// Serve the application at the given port
app.listen(port, () => {
const source = fs.createReadStream('/src/app');
const dest = fs.createWriteStream('/dist');
source.pipe(dest);
source.on('end', function() { /* copied */ });
source.on('error', function(err) { /* error */ });
// Success callback
console.log(`Listening at http://localhost:${port}/`);
});
What would be the way to display my templates with the files showing?
I was doing this wrong app.use( express.static( "template" ) );
I should be doing app.use(express.static(__dirname + '/app/template'));
i think you need to define what the root directory is first in express before importing assets (at least, it helps!)
so if you import express and then assign express() to a variable ,e.g.
var express = require express();
var app = express;
then you could do something like:
var root = require('path').join(__dirname,'/template');
app.use(express.static(root));
Once the root is defined, all further files will be called from that place when a url is referenced.
hope this helps