I've been following along with a PERN stack tutorial from YouTube and I've started running into problems with using the require function in the index file for my server application running Node v 17.7.2 with Express 4.17.
The code that's throwing the errors is here:
const express = require("express");
const app = express();
const cors = require("cors");
const routes = require("./routes/jwtAuth")
app.use(express.json());
app.use(cors());
app.use('/auth', myRoutes);
app.get('/', (req, res) =>{
res.send('hello world!');
});
app.listen(process.env.PORT, ()=>
console.log('listening at port 3000'),
);
The error I get is:
const express = require("express");
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/Nizz0k/Sites/pgpengapi/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
From what I've read this error used to be limited to using require() in frontend code, but after Node v14 can happen in server scripts as well. I have the type set to module. The error seems to be relatively recent, as I've not had any crashing changes when using require in the app up to now.
When you use ES modules (ie. when you set type to module), you need to use the import syntax:
import express from 'express';
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'm unable to run a node terminal on my backend server.js file in my class project. I am NOT running this in my browser, I'm trying to run my localhost through my node terminal. I've tried looking through a few articles, I made sure that requirejs was installed, babel is installed, I've tried substituting in "import" rather than require, and to my knowledge, all of the necessary files are installed in my package.json.
When I run nodemon server, or node server, I get the following error message
const express = require('express');
^
ReferenceError: require is not defined
This is the code so far.
const express = require('express');
const cors = require('cors');
// const mongoose = require('mongoose');
const mongoose = require('mongoose')
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });const connection = mongoose.connection;connection.once('open', () => { console.log("MongoDB database connection established successfully");})
const addLocationsRouter = require('./routes/addLocations.models');
const contactsRouter = require('./routes/contacts.models');
const homeRouter = require('../src/components/Home')
const allLocationsRouter = require('../src/components/alllocations')
app.use('/allLocations', allLocationsRouter)
app.use('/Home', homeRouter);
app.use('/addLocations', addLocationsRouter);
app.use('/contacts', contactsRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
I've used require in other parts files in my backend folder and it doesn't throw an error. However, in my server.js file, I seemingly can't use the word require
Ok, I think I have it
uninstall axios, babel, and requirejs. You don't actually use those packages in your back end.
Then remove "type": "module" from your package.json
According to this issue, you should remove "type": "module" from your package.json file.
Can you verify that this happens in any directory? By default a .js file shouldn’t be treated as a module. I suspect that you may be in a directory (or nested directory below) where a package.json has a “type” field set to “module”.
#jkrems You are right. The module "type" was causing the issue. Thank you for flagging that out.
In addition, you have to ensure that you are requiring dotenv in the backend (in your file that has express), rather than in your frontend javascript files.
I'm new to NodeJs and express. My goal is to have a separate route file that contains all my application routes. So I created a file called routes.js. The content looks like this:
const express = require('express');
const router = express.Router();
router.get('auth/register', require('./controllers/auth/register'));
module.exports = router;
In my main file, I require the file with this line. The app variable contains my express instance.
app.use('/', require('./routes'));
If I call http://localhost/auth/register in my browser, I'm always running into a 404 Not Found error. When I define the route directly in the main file with app.get('/auth/register', require('./controllers/auth/register')); it works well. There are no errors in my console.
Has anyone an idea why my sperate route file does not work? Thank you for your help!
Traditionally, I do the following which is to pass the express instance into your routes module:
once I have instantiated my express instance called app
app.js
require('./routes.js')(app);
routes.js where registerUser us the function to call when the route is matched
module.exports = (app) => {
app.route('/auth/register')
.post(registerUser);
}
You want to pass app into your routes file. A good pattern for this is to import your routes in your main file, like const routes = require('./routes');
In routes, you can define all of your routes like so:
module.exports = (app, router) => {
router.route("/").get()
router.route("/something_else").post()
app.use("/api", router)
...
};
This way, in your main file, you can do: routes(app, router) and have access to app and router inside your routes.js.
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);
Say for example in my node_module folder I have an npm called project which has some set defined express routes. For example,
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('indexPage', {title: 'Homepage'});
});
module.exports = router;
which is kept in a routes.js file
How would this be accessed in the main node project file index.js file?
I have attempted to use require() function, however, this doesn't work.
After you set your app as an Express app then add your routes middleware(s) like the below.
Also I've added some useful code parts (a simple Express app) for any beginner:
// defining an express app
var express = require('express')
var app = express()
var server = require('http').Server(app)
// setting the express app - in case of needed
app.set('x-powered-by', false) // hide x-powered-by header!
app.set('view engine', 'ejs'); // set EJS as view engine!
app.set('views', __dirname + '/views'); // specifying the directory that contains view files
// THIS IS YOUR ANSWER PART
app.use(require('./routes'))
...
...
// Other middlewares
app.use(require('./middlewares/someMiddleware'))
// Catching 404 errors
app.use('*', function(req,res){
res.status(404).send("URL not found.")
})
// Catching and evaluating the other errors
app.use(require("./middlewares/errorHandler"))
server.listen(3001, function() {
console.log('APP Server is listening HTTP port 3001')
})
Generally the last route is been 404 error. So, if the request has not been caught in any route before 404, that means "the page cannot found".
Also, errorHandler middleware takes 4 arguments (error, request, response and next).
So, if you encountered with an error in your routes.js, and if you send this error in routes files by using next(err) this error can be caught on errorHandler middleware.
This is basic information which everyone needs when starting to develope an Express application.
For more details:
http://expressjs.com/en/guide/using-middleware.html
Good luck...