I'm using sass with node app, for that I have installed this dependency "npm install node-sass-middleware". It's not generating the style.css file means not compiling the style.scss file. And I'm using express. Please help
Code in my app.js
app.use(sassMiddleware({
src: path.join(__dirname, 'public/scss'),
dest: path.join(__dirname, 'public/css'),
debug: true,
indentedSyntax: true,
outputStyle: 'compressed'
}));
// Static folder
app.use(express.static(path.join(__dirname, 'public')));
thanks in advance
app.js
var express = require('express');
var sass = require('node-sass');
var sassMiddleware = require('node-sass-middleware');
var path = require('path');
const app = express();
app.set('view engine', 'ejs');
app.use(sassMiddleware({
src: path.join(__dirname, 'public/scss'),
dest: path.join(__dirname, 'public/css'),
debug: true,
indentedSyntax: false,
outputStyle: 'compressed',
prefix: '/css'
}));
// Static folder
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req,res)=>{
res.render('index');
});
app.get('/download', function (req, res, next) {
var filePath = "public/files/Bijitashya (2).doc"; // Or format the path using the `id` rest param
var fileName = "Bijitashya (2).doc"; // The default name the browser will use
res.download(filePath, fileName);
});
const port = process.env.PORT || 5000;
app.listen(port, () =>{
console.log(`Server started on port ${port}`);
});
package.json
{
"name": "portfolio",
"version": "1.0.0",
"description": "My Portfolio",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"author": "Bijitashya",
"license": "ISC",
"dependencies": {
"bootstrap": "4.0.0",
"ejs": "^2.5.7",
"express": "^4.16.3",
"font-awesome": "^4.7.0",
"jquery": "^3.3.1",
"node-sass": "^4.9.0",
"node-sass-middleware": "^0.11.0",
"popper.js": "^1.12.9"
}
}
Assuming from your directory name, you have .scss files that you need to compile. With the optionindentedSyntax: true the middleware will try to find .sass files instead of .scss files. So if you don’t have any .sass files, it won’t be any output or compiled files
You just need to set the option to false or just remove the option, as false is the default value for it.
Related
I am trying to deploy MERN App on Vercel but getting NOT FOUND
When i put NODE_ENV as PRODUCTION then it works fine and serves the static files on local machine when run npm start but it is not working on vercel.
.
My Directory Structure is
My app.js file is
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const PostRoutes = require("./Routes/posts");
const CategoryRoutes = require("./Routes/categories");
const UserRoutes = require("./Routes/user");
const AuthRoutes = require("./Routes/auth");
const bodyParser = require("body-parser");
const multer = require("multer");
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/images/");
},
filename: (req, file, cb) => {
cb(null, Date.now() + "_" + file.originalname);
},
});
var upload = multer({ storage: storage });
const cors = require("cors");
dotenv.config();
app.use(express.json());
app.use("uploads/images/", express.static("uploads/images/"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV == "production") {
const path = require("path");
app.get("/", (req, res) => {
app.use(express.static(path.resolve(__dirname, "frontend", "build")));
res.sendFile(path.resolve(__dirname, "frontend", "build", "index.html"));
});
}
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(console.log("connected to Mongo database "))
.catch((err) => {
console.log(err);
});
app.use("/api/posts", upload.single("photo"), PostRoutes);
app.use("/api/categories", CategoryRoutes);
app.use("/api/auth", upload.none(), AuthRoutes);
app.use("/api/users", upload.single("profile_pic"), UserRoutes);
app.listen(process.env.PORT || 3001, () => {
console.log(`Server Listening on the port ${process.env.PORT}`);
});
package.json file
{
"name": "backend",
"version": "1.0.0",
"description": "Backend to the blog app ",
"main": "app.js",
"scripts": {
"start": "node app.js",
"dev-start": "nodemon app.js --ignore client",
"start-client": "npm start --prefix frontend",
"dev": "concurrently \"cd ./frontend && npm start\" \"npm run dev-start\""
},
"author": "Shiv Shankar Prasad",
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.0",
"concurrently": "^7.4.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-async-handler": "^1.2.0",
"express-validator": "^6.14.2",
"jsonwebtoken": "^8.5.1",
"minifaker": "^1.34.1",
"mongoose": "^6.5.3",
"multer": "^1.4.5-lts.1",
"nodemon": "^2.0.19"
}
}
Please help.
I have found a solution and it was the changes in the vercel.json file.
Now i used the vercel CLI and it is much more easy to use.
{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/"
}
]
}
I keep getting a error "MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.". I've been looking at other questions that get a similar error butI did not find a solution after trying multiple different things.
in package.json
{
"dependencies": {
"bcrypt": "^5.1.0",
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"gridfs-stream": "^1.1.1",
"helmet": "^6.0.1",
"jsonwebtoken": "^9.0.0",
"mongoose": "^6.7.0",
"morgan": "^1.10.0",
"multer": "^1.4.4",
"multer-gridfs-storage": "^5.0.2"
},
"name": "server",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
in index.js
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import multer from "multer";
import helmet from "helmet";
import morgan from "morgan";
import path from "path";
import { fileURLToPath } from "url";
/* CONFIGURATIONS */
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
app.use(express.json());
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use("/assets", express.static(path.join(__dirname, "public/assets")));
/* FILE STORAGE */
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "public/assets");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({ storage });
/* MONGOOSE SETUP */
const PORT = process.env.PORT || 6001;
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
})
.catch((error) => console.log(`${error} did not connect`));
in .env
MONGO_URL = 'the connection string'
PORT = 3001
Getting a Strange Error I have tried Everything but My code Doest not pick up Req.file..
I AM new to Nodejs And Express, AND i was try to upload an image using multer.
Req.file is showing UNDEFINED and Image is not uploading
This is my source code with using PUG(template engine)
Bumper.pug
extends base.pug
block style
style
include ../static/productUpload.css
block scripts
script(src="../static/categorienav.js")
//- script(src="../static/productid.js")
block content
p.heading
| Upload BUMPER
.UploadPage
.Uploadinfo
p#PID BUMPER
form.uploadform(action=`/BumperUpload` , method="post" enctype="multipart/form-data")
input.catsclass(type="file",name="file" accept="image/*" required)
input.catsclass(type="text",name="Link",placeholder="paste Link here" required)
input.catsclass(type="submit")
| #{Change}
Bumper.js
var express = require('express');
var myrouter= express.Router();
var bodyparser = require('body-parser');
var fs = require('fs');
var multer = require('multer');
// Initialize the express object
var app = express();
// Use body-parser to parse incoming data
app.use(bodyparser.urlencoded({extended : true}))
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', [__dirname + '/views', __dirname + '/views2']); // Set the views directory
myrouter.get('/BumperUpload',(req,res)=>{
res.render('Bumper.pug');
})
var storage = multer.diskStorage({
destination: function (request, file, callback) {
callback(null, './uploads/');
},
filename: function (request, file, callback) {
console.log(file);
callback(null, file.originalname)
}
});
var upload = multer({ storage: storage });
myrouter.post('/BumperUpload', upload.single('file'), function (req, res) {
console.log(req.file);
if (req.file) {
console.log('Uploading File');
var profileImageOriginlName=req.file.originalname;
var profileImageName=req.file.name;
var profileImageMime=req.file.mimetype;
var profileImagePath=req.file.path;
var profileImageExt=req.file.extension;
var profileImageSize=req.file.size;
}
else
{
var profileImageName='noimage.png';
}
console.log(profileImageName);
res.send("done")
});
module.exports = myrouter;
Index.js
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const port = 80;
const bodyparser = require('body-parser')
// var http = require('http');
const fileUpload = require('express-fileupload');
var nodemailer = require('nodemailer');
// var mail = require("./static/mail.js")
//////mongojson = require("./mongodb.js")
var domain = require("domain").create();
var mongoose = require('mongoose');
var HOME = require('./models/HOME/HOME.js')
var Bumper = require('./models/HOME/Bumper.js');
var MongoClient = require('mongodb').MongoClient;
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded());
app.use(fileUpload());
// PUG SPECIFIC STUFF
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', [__dirname + '/views', __dirname + '/views2']); // Set the views directory
app.use('/', Bumper);
// START THE SERVER
app.listen(port, () => {
// //console.log(res);
//console.log(`The application started successfully on port ${port}`);
});
package.json
{
"name": "rk",
"version": "1.0.0",
"description": "",
"main": "param.js",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"bootstrap-icons": "^1.1.0",
"connect-busboy": "0.0.2",
"connect-flash": "^0.1.1",
"cookie-parser": "^1.4.5",
"crypto": "^1.0.1",
"domain": "0.0.1",
"express": "^4.17.1",
"express-fileupload": "^1.2.0",
"express-session": "^1.17.1",
"filesystem": "^1.0.1",
"formidable": "^1.2.2",
"jquery": "^3.5.1",
"jsonwebtoken": "^8.5.1",
"localStorage": "^1.0.4",
"method-override": "^3.0.0",
"mongodb": "^3.6.3",
"mongoose": "^5.10.14",
"multer": "^1.4.2",
"nodemailer": "^6.4.16",
"passport": "^0.4.1",
"passport-local": "^1.0.0",
"pug": "^3.0.0"
},
"devDependencies": {},
"scripts": {
"start": "nodemon param.js"
},
"author": "RISHABH GARG",
"license": "ISC"
}
Result:
Database Connected <br>
undefined // req.file is showing undefined<br>
noimage.png //image is not upload<br>
Hey I got the solution I Uninstall the Express-FileUpload and now it works
I'm currently trying to learn MEAN stack. The tutorial are about a task manager. Right now I'm trying to connect to mongodb atlas to retrieve sample data in database but they are not showing up http://localhost:3000/api/tasks
Here is my tasks.js file
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('drivers',['tasks']);
router.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
module.exports = router;
Here is my server.js file
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var task = require('./routes/tasks');
var app = express();
var port = 3000;
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('/api', task);
app.listen(port, function(){
console.log('Server started on port' +port);
});
Here is my package.json file
{
"name": "mytasklist",
"version": "1.0.0",
"description": "Task Manager",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"ejs": "^2.6.1",
"express": "^4.17.1",
"mongojs": "^2.6.0"
}
}
Problem solved, I pasted the wrong version for my nodejs driver.
need to use mongojs version 3.0.0 to connect to atlas
I have already run my nodejs app successfully on my localhost, but when I deploy it on heroku, build success, but I got a "Application Error", when I use "heroku logs", it show like this:
console screenshot
I can't figure out what's wrong with my app, hope to get your help, thanks!
Here's my package.json
{
"main": "index.js",
"scripts": {
"test": "mocha --harmony test",
"start": "cross-env NODE_ENV=production pm2 start index.js --node-args='--harmony' --name 'adolt-blog'"
},
...
"dependencies": {
"config-lite": "^1.5.0",
"connect-flash": "^0.1.1",
"connect-mongo": "^1.3.2",
"cross-env": "^3.1.3",
"ejs": "^2.5.2",
"express": "^4.14.0",
"express-formidable": "^1.0.0",
"express-session": "^1.14.2",
"express-winston": "^2.0.0",
"marked": "^0.3.6",
"moment": "^2.17.0",
"mongolass": "^2.3.2",
"objectid-to-timestamp": "^1.3.0",
"sha1": "^1.1.1",
"winston": "^2.3.0",
"pm2": "^2.2.3",
"mocha": "^3.2.0"
}
}
and index.js
var path = require('path');
var express = require('express');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var config = require('config-lite');
var routes = require('./routes');
var pkg = require('./package');
var winston = require('winston');
var expressWinston = require('express-winston');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
name: config.session.key,
secret: config.session.secret,
cookie: {
maxAge: config.session.maxAge
},
store: new MongoStore({
url: config.mongodb
}),
saveUninitializedSession: true,
resaveSession: true
}));
app.use(flash());
app.use(require('express-formidable')({
uploadDir: path.join(__dirname, 'public/img'),
keepExtensions: true
}));
app.locals.blog = {
// title: pkg.name,
// description: pkg.description
title: 'Adolt\'s Blog',
description: 'Learn Node.js'
};
app.use(function (req, res, next) {
res.locals.user = req.session.user;
res.locals.success = req.flash('success').toString();
res.locals.error = req.flash('error').toString();
next();
});
app.use(expressWinston.logger({
transports: [
new (winston.transports.Console)({
json: true,
colorize: true
}),
new winston.transports.File({
filename: 'logs/success.log'
})
]
}));
routes(app);
app.use(expressWinston.errorLogger({
transports: [
new winston.transports.Console({
json: true,
colorize: true
}),
new winston.transports.File({
filename: 'logs/error.log'
})
]
}));
if (module.parent) {
module.exports = app;
} else {
const port = process.env.PORT;
app.listen(port, function () {
console.log(`${pkg.name} listening on port ${port}`);
});
}
Thanks to the help of #Lucas Katayama, the problem finally solved.
First, add main.js according to the use-pm2-with-cloud-providers.
And then modify the Procfile like this
web: node main.js
Finally, rebuild your app and see if it works!
Hope it can help! Good luck!