For some reason i am having this error "ReferenceError: require is not defined" and i cant figure out why ?. Has anyone got an idea how i can fix this ? i am trying to connect my e-commerce website to mongodb
here's the code
.env file
PORT=5000
MONGO_URL = mongodb+srv://nashmaj:frzw14qa#cluster0.52b6h.mongodb.net/e-commerce-webapp?retryWrites=true&w=majority
server.js file
require("dotenv").config();
const express = require('express')
const app = express();
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser');
// const { Console } = require('console');
const PORT = process.env.PORT || 5000
app.use(express.json())
app.use(cookieParser())
app.use(cors)
app.use(fileUpload({
useTempFiles: true
}))
//connect to db
const URL = process.env.MONGO_URL
mongoose.connect({
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology:true
}, err=> {
if (err) throw err;
console.log('Connected to Mongo DB')
})
app.get('/', (req, res) => {
res.json({msg: "Welcome"})
})
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
You can check if you have configured node to use ES Modules. This is in package.json
"type": "module",
Remove this line and check again.
Remember that having "type": "module"you cannot use require and instead you need to use import syntax.
Related
So I have a full stack website and the frond end is hosted on netlify via github and the backend is hosted on heroku. When I make changes on front end I have to push each change to github in order to see the result. I am a newbie and I do not know how should I work on a project locally when all my routes are netlify and heroku routes.
This is the code
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const User = require("./models/userModel");
dotenv.config();
// set up server
const app = express();
app.listen(process.env.PORT || 5000, () =>
console.log(`Server started on port: ${process.env.PORT || 5000 }`)
);
app.get("/test", (req, res) => {
res.send("It works");
});
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
origin: "https://awesome-murdock-.netlify.app/",
credentials: true,
})
);
// connect to mongoDB
mongoose.connect(
process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) return console.error(err);
console.log("Connected to MongoDB");
}
);
// sign
// set up routes
app.use("/auth", require("./routers/userRouter"));
app.use("/customer", require("./routers/customerRouter"));
app.get('/', (req, res) => {
res.send('Hi')
})
as you can see cors is ponting to my netlify app and it has not connection with my back end and the same is with backend
const express = require('express');
const app = express();
//set up handlebars
const handlebars = require('express-handlebars');
app.engine("handlebars",handlebars())
app.set("view engine", "handlebars")
const sqlite3 = require('sqlite3');
const sqlite = require('sqlite');
const port = 8080
const dbPromise = sqlite.open({
filename:"./database/sakila.sqlite",
driver: sqlite3.Database
})
app.get("/",(req,res)=>{
res.render("home",{layout:false});
})
app.listen(port,()=>{
console.log(`server running on ${port}`);
})
I was following a lecture video to learn about handlebars. I typed the same code word by word to set up handlebars and I did npm install express-handlebars --save. The instructor's code is working but mine is not.
It only warns me that
"app.engine("handlebars",handlebars())
^
TypeError: handlebars is not a function
"
I couldn't figure out why. Please help. Thank you in advance.
const express = require("express");
const handlebars = require("express-handlebars");
const app = express();
//set up handlebars
app.engine("handlebars", handlebars());
app.set("view engine", "handlebars");
const sqlite3 = require("sqlite3");
const sqlite = require("sqlite");
const port = 8080;
const dbPromise = sqlite.open({
filename: "./database/sakila.sqlite",
driver: sqlite3.Database
});
app.get("/", (req, res) => {
res.render("home", { layout: false });
});
app.listen(port, () => {
console.log(`server running on ${port}`);
});
I want to connect my database using .env file but I am getting an error:
I tried console logging my .env variable but I am getting Undefined:
Here are my scripts:
server.js
require("dotenv").config({ path: "./config.env" });
const express = require("express");
const app = express();
const connectDB = require("./config/db");
// Connect DB
connectDB();
app.use(express.json());
app.use("/api/auth", require("./routes/auth"));
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Sever running on port ${PORT}`)
);
console.log("```` DB NAME ````", process.env.DATABASE_CONNECTION);
process.on("unhandledRejection", (err, promise) => {
console.log(`Logged Error: ${err.message}`);
server.close(() => process.exit(1));
});
db.js
const mongoose = require("mongoose");
const connectDB = async () => {
await mongoose.connect(process.env.DATABASE_CONNECTION, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: true,
});
console.log("MongoDB Connected");
};
module.exports = connectDB;
config.env
PORT=5000
DATABASE_CONNECTION=mongodb://localhost:27017/node_auth
I have checked other solutions, but none of them helped.
This solved my issue:
require("dotenv").config({
path:
"C:/Users/.../auth/config.env",
});
Basically, write whole path of the file.
I created a Nuxt app with express backend, and i have registered some api routes. When i run locally as production npm run build && npm run start it works just fine.
Here it is working locally
However when i run it with heroku heroku local web all the API routes throw a 404.
Here it doesn't work with heroku
Here is my server code
require('dotenv').config();
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const bodyParser = require('body-parser');
const session = require('express-session');
const mongoose = require('mongoose');
const cors = require('cors');
mongoose.Promise = Promise;
mongoose.set('useFindAndModify', false);
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
const app = express();
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js');
config.dev = process.env.NODE_ENV !== 'production';
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config);
const { host, port } = nuxt.options.server;
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt);
await builder.build();
} else {
await nuxt.ready();
}
app.use('/api', require('./routes'));
// session
app.use(
session({
sessionDataHere
})
);
// enable cors
app.use(cors());
// body parser
app.use(bodyParser.json());
app.use((error, req, res, next) => {
console.error(error.response);
res.status(500).send(error);
});
// Give nuxt middleware to express
app.use(nuxt.render);
// Listen the server
app.listen(port, host);
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
});
}
start();
And here is the index of my routes
const { Router } = require('express');
const authRouter = require('./auth');
const videoRouter = require('./video');
const baseRouter = Router();
baseRouter.use('/', authRouter);
baseRouter.use('/', videoRouter);
baseRouter.get('/test', (req, res) => res.send('This is working!'));
module.exports = baseRouter;
Maybe i'm missing something on the heroku configuration? Thanks!
Ok, i fixed it. I had to change my procfile. It was running nuxt start not npm start so it wasn't running any of the server side code
I am trying to serve an angular app using nodejs. But i get this error
"Cannot GET /" in the body of the page. I tried a number of things but still this does not work. do you folks have any suggestion?
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
app.listen(5000, () => console.log('Listening on port 5000'))
////////////////////////////////////////
// View
////////////////////////////////////////
const viewOptions = { include_docs: true }
app.route('/api/schedules').get((req, res) => {
couchDb.getType('schedule', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/stations').get((req, res) => {
couchDb.getType('station', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
app.route('/api/tests').get((req, res) => {
couchDb.getType('testConfig', viewOptions).then(docs => {
res.send(docs)
}).catch(err => {
console.log(err)
res.send({})
})
})
you are missing your routes e.g
app.get('/', function (req, res) {
res.send('hello world')
})
or you need to include your all routes through middle ware.
You are getting that error because you are not declaring any endpoints or telling the server to serve anything. It is listening on port 5000, but no responses to any urls have been defined. Here is a piece of example code that will resolve your issue.
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
// This block will make it so that every path on port 5000 responds with "Hello, World!"
app.get('*', (req, res) => {
res.status(200).send("Hello, World!");
});
app.listen(5000, () => console.log('Listening on port 5000'))
This will make it respond with basic text, if you want to serve an angular application, you will need to look into serving static content from express: https://expressjs.com/en/starter/static-files.html
You have to use a routing middleware and map your modules to the required modules.Also make sure your modules are mounted in router instance.
Something like
const express = require('express')
const app = express()
var cors = require('cors')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const couchDb = require('./modules/couchDb')
const db = couchDb.db
const schedules = require('./modules/schedules')
const stations = require('./modules/stations')
const testConfigs = require('./modules/testConfigs')
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(fileUpload())
//All requests with /schedules will go to './modules/schedules'
app.use('/schedules', schedules);
app.use('/stations', stations);
app.listen(5000, () => console.log('Listening on port 5000'))
your ./modules/station should look like
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('You are in /station')
})
router.get('/new', function (req, res) {
res.send('You are in /station/new')
})
module.exports = router
For more : https://expressjs.com/en/guide/routing.html