Why my Express Static Folder aren't Working Properly - node.js

why my static folder isn't working if I use Cloudinary and express-fileupload for profile IMG (client-side) upload and multer for post cover image upload only one of them are working if comment out the other one please help me to get rid of this problem...
const express = require("express");
const cors = require('cors');
const fileUpload = require('express-fileupload');
const app = express();
app.use(cors());
// Below code is for client side profile photo upload it is stores in cloudinary
app.use(fileUpload({
useTempFiles: true
}));
// Below code is static post cover photo it is stores in static folder in backend
app.use('/', express.static('uploads'));
app.get("/", (req, res, next) => {
res.send("Api running");
});
// Connecting Routes
app.use('/', require('./routes/indexpost'));
app.use('/user', require('./routes/userRouter'));
app.use('/api', require('./routes/upload'));

Related

how to include static files (html ,css) in express.js

i am not able to include static CSS file in the express app
I have used app.use(express.static('public') still in the output file CSS in not include
// initialize modules // ATHARVA BHAVSAR
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
//creating app from express method
const app = express();
//body parser
app.use(bodyParser.urlencoded({ extended: true }));
//including static files in the app
app.use(express.static("public"));
//get method for the app
app.get("/", (req, res) => {
res.sendFile(__dirname + "/signup.html");
});
//post method for the app
app.post("/", (req, res) => {
//getting the entries from the user
const FirstName = req.body.Fname;
const LastName = req.body.Lname;
const Email = req.body.email;
//trial
console.log(FirstName, LastName, Email);
});
//listening to port 3000
app.listen(3000, function () {
console.log("Server is running on port 3000");
});
Well, you're including the static files correctly, but how are your folder structure looking like? since you called app.use(express.static("public")); your css should be inside a folder called "public", also can I take a look at your html? You still need to link your css in your html file, you know right?

why are my static files failing to load response

i am trying to get data from a html form using express
but when i try to load my static files with app.use(express.static(__dirname+"public");
in the devtools it is showing that it failed to load my response data
can anyone tell me why this is happening and a solution for this
here is the code in the first image
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static(__dirname+'public'));
app.get("/",function(req,res){
res.sendFile(__dirname + "/public/bmiCalculator.html");
});
app.post("/",function(req,res){
console.log(req.body);
res.send("hello");
});
app.listen(300,function(){
console.log("Server Hosted OK");
});
The path provided to the static middleware is incorrect. The following code __dirname+'public' will give you Calculatorpublic, i.e. / is missing. What you can do is to add the / before public:
app.use(express.static(__dirname, "/public"));
Another variation:
const path = require('path');
app.use(express.static(path.join(__dirname, "public")));

How to export axios requests on node js from my routes files to the main app.js?

I have a folder for my routes, so I want to export the routes to my app.js using axios.
I just don't know how to add this axios routes to my app.js file as I do with normal routers from express.Router()
This is my USER.JS file inside routes folder on my porject:
const express = require('express')
const router = express.Router()
const userController = require('../controllers/userController')
const axios = require('axios')
router.get('/user', userController.getUserLogin)
router.get('/userRegister', userController.getUserRegister)
router.post('/user', userController.postUserLogin)
router.post('/userRegister', userController.postUserRegister)
module.exports = axios.get('/user', userController.getUserLogin)
module.exports = router
This is my app.js:
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const userRoutes = require('./routes/user')
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({ extended: false }))
app.set('view engine', 'ejs')
app.use('/', userRoutes)
app.listen(process.env.PORT || 5000, () => {
console.log(`application running`)
})
how to add this axios routes
Simple answer: There's no axios routes
From npm axios describes itself as:
Promise based HTTP client for the browser and node.js
Notice the word client. It's a client not server. Its function is to make http calls to some resource served by server.
From npm, the top 2 listed features
Make XMLHttpRequests from the browser
Make http requests from node.js
To make express routes you either use instance of default express class or express.Router() class.
const express = require('express')
const app = express();
// route
app.get('/myroute', (req, res) => {})
// using Router
const router = express.Router()
router.get('/myroute', (req, res) => {})

How to configure Express app with Vue Router?

I'm building an Express based app that works as follows:
'/' static main site served by Express with pug templating engine
'/admin' admin panel handled by VueJS with Vue Router in history mode
At the moment if I go to '/admin/about' it works fine, but when I refresh the page it throws the 404 error. How do I configure the server to handle all admin routes ('/admin/xxx') with Vue Router but all main site routes with Express (as it currently does)?
I've tried using connect-history-api-fallback middleware but with no success.
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const history = require('connect-history-api-fallback');
const adminRoutes = require('./routes/admin');
const publicRoutes = require('./routes/index');
app.set('view engine', 'pug');
app.set('views', 'views');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminRoutes);
app.use(publicRoutes);
app.use(history());
app.use((req, res, next) => {
res.status(404).render('404', {
pageTitle: 'Page Not Found'
});
});
app.listen(3000);
routes/index.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
res.render('home/index', {
pageTitle: 'Lorem Ipsum',
path: '/'
});
});
module.exports = router;
routes/admin.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
res.render('admin/index', {
pageTitle: 'Admin Panel',
path: '/'
});
});
module.exports = router;
Your current configuration handles just root path / for the admin SPA(so you get 404 on all admin pages except the root if you tries to refresh page). You can allow all admin urls to be "processed" by Vue app on client(even 404 errors) with /* instead of / in your route.
But there will be a problem with http status codes because (as you probably guessed) server will always return 200 for every route... but I think most of developers are ok with this and just showing some 404-page-component for user if there is no component matched the url.
If you want to see correct http codes in your browser for web consistency, debugging, project requirements or something - without SSR, you will have to repeat your client routes in back-end I think.

NodeJs routes not working from inner page

I am trying to develop an application in NodeJs using express framework. My routing is working when I navigating from home to inner pages. But If I want to navigate from some inner page to homepage then it is not working.
Below is my app.js code.
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
//declare all routers
var home = require(path.join(__dirname, "/routes/index"));
var myaccount = require(path.join(__dirname, "/routes/myaccount"));
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('html', engines.handlebars);
var defaultViewPath = path.join(__dirname, "/views");
app.set('views', defaultViewPath);
app.set('view engine', 'html');
app.use('/', home);
app.use('/myaccount', myaccount);
Here if I have navigated from home to myaccount - Its working
But if I am navigating from myaacount to home - It reloads the same page.
Can anyone help me to resolve this issue.
To define routing using methods of the Express app object, use app.get() to handle GET requests
var express = require('express')
var app = express()
// When GET request is made to the homepage
app.get('/', function (req, res) {
res.render('home');
});
// When GET request is made to the myaccount
app.get('/myaccount', function (req, res) {
res.render('myaccount');
});
app.get('/myaccount/innerpage', function (req, res) {
res.send('Hello Inner Page');
});
//Page Not Found
app.use(function(req, res){
//render the html page
//res.render('404');
res.sendStatus(404);
});
Hope this could help you
use app.get and app.post Route Methods
app.get('/',function(req,res){
res.render('home');
});
app.get('/myaccount',function(req,res){
res.render('myaccount');
});
Or Create Router File For Home & myAccount
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Home Page')
})
module.exports = router
in Your app.js or index.js file , require route.js
var home = require('./route');
app.use('/', home)

Resources