I'm stuck in this error...I'm trying but I can not fix it
This is my index.js file
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
const app = express();
dotenv.config();
const connect = async () => {
try {
await mongoose.connect(process.env.MONGO);
console.log("Connected to mongoDB.");
} catch (error) {
throw error;
}
};
mongoose.connection.on("disconnected", () => {
console.log("mongoDB disconnected!");
});
app.listen(3000, () => {
connect();
console.log("Connected to backend.");
});
This is my pacakge.json file
{
"name": "quiz-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.2",
"express": "^4.18.1",
"mongoose": "^6.5.4"
},
"devDependencies": {
"webpack-cli": "^3.3.12"
}
}
when I run this app it shows this error
enter image description here
You are using ES6 style importing import express from "express"; but your package.json doesn't know about that. Because the default is CommonJS for Node.js right now. And that means it wants you to use const express = require("express");
If you want to change that to ES6, you need to add "type": "module", in your package.json.
For example:
...
"description": "",
"type": "module",
"main": "index.js",
...
Related
server.js
import express from 'express';
import { routes } from './routes';
import { db } from './db';
const app = express();
app.use(express.json());
routes.forEach(route => {
app[route.method]('/api' + route.path, route.handler);
});
const start = async () => {
await db.connect('mongodb://localhost:27017');
await app.listen(8080);
console.log('Server is listening on port 8080');
};
start();
one route deleteIngredientRoute.js
import { deleteIngredient, getIngredients } from '../db';
export const deleteIngredientsRoute = {
path: '/meals/:name',
method: 'DELETE',
handler: async (req, res) => {
const { name } = req.params;
await deleteIngredient(name);
const updatedIngredients = await getIngredients();
res.status(200).json(updatedIngredients);
},
};
package.json
{
"name": "fsa-back-end-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "npx nodemon --exec 'npx babel-node src/server.js'"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.20"
},
"dependencies": {
"#babel/cli": "^7.19.3",
"#babel/core": "^7.20.2",
"#babel/node": "^7.20.2",
"#babel/preset-env": "^7.20.2",
"#babel/register": "^7.18.9",
"express": "4.17.1",
"mongodb": "4.1.0"
}
}
Error
app[route.method]('/api' + route.path, route.handler);
^
TypeError: app[route.method] is not a function
Also sometimes i get this error
''npx' is not recognized as an internal or external command,
operable program or batch file.
[nodemon] app crashed - waiting for file changes before starting...
I am using NVM i added to environment Path variables
node:internal/errors:477
ErrorCaptureStackTrace(err);
^
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './' is not defined by "exports" in C:\Users\Dell\Music\insta_app\node_modules\graphql-tools\package.json imported from C:\Users\Dell\Music\insta_app\schema.js
package.json
{
"name": "insta_app",
"version": "1.0.0",
"description": "",
"main": "server.js",
"type": "module",
"scripts": {
"start": "nodemon --exec node server.js",
"migrate": "npx prisma migrate dev"
},
"author": "",
"license": "ISC",
"dependencies": {
"#graphql-tools/load-files": "6.6.1",
"#graphql-tools/merge": "8.3.4",
"#prisma/client": "^4.3.0",
"apollo-server": "^3.10.2",
"dotenv": "^16.0.2",
"graphql": "^16.6.0",
"graphql-tools": "^8.3.4"
},
"devDependencies": {
"prisma": "^4.3.0"
}
}
server.js
import * as dotenv from 'dotenv'
dotenv.config()
import {ApolloServer , gql} from "apollo-server" ;
import schema from "./schema.js";
// import Client from './prisma/client';
const server = new ApolloServer({
schema,
});
const PORT = process.env.PORT
server.listen(PORT);```
schema.js```
import { makeExecutableSchema, mergeResolvers } from "graphql-tools";
import {mergeTypeDefs} from 'graphql-tools/';
import { loadFilesSync } from '#graphql-tools/load-files';
const loadTypes =loadFilesSync(`${__dirname}/**/*.typeDefs.js`);
const loadResolvers = loadFilesSync(`${__dirname}/**/*.{mutations, queries}.js`);
const TypeDefs = mergeTypeDefs(loadTypes);
const Resolvers = mergeResolvers(loadResolvers);
const schema = makeExecutableSchema(TypeDefs,Resolvers);
export default schema;
When trying to create a rest api using node js to connect to my database. Following is my code.
The database connection is not working
enter image description here
My Dbconfig file
const config = {
user:'DESKTOP-HLJJ615\RIDERZONE',
password:'',
server:'DESKTOP-HLJJ615\SQLEXPRESS',
database:'Movie',
options:{
trustedconnection: true,
enableArithAort: true,
instancename: 'SQLEXPRESS'
},
port: 49675
}
module.exports = config;
my api.js file
var Filmnode = require('./Film8node');
const dboperations = require('./dboperations');
dboperations.getFilm().then(result => {
console.log(result);
})
My dboperations.js file
var config = require('./dbconfig');
const sql = require('mssql');
async function getFilm(){
try{
let pool = await sql.connect(config);
let films = await pool.request().query("SELECT * from Film8node");
return films.recordsets;
}
catch (error){
console.log(error);
}
}
module.exports ={
getFilm : getFilm
}
My filmnode.js file
class Filmnode{
constructor(Film_id,film_name,actor,actress,pub_date,director,producer,prod_cost,dist_cost,category,cert_category,poster){
this.Film_id=Film_id;
this.film_name=film_name;
this.actor=actor;
this.actress=actress;
this.pub_date=pub_date;
this.director=director;
this.producer=producer;
this.prod_cost=prod_cost;
this.dist_cost=dist_cost;
this.category=category;
this.cert_category=cert_category;
this.poster=poster;
}
}
module.exports = Filmnode;
my package.json file
{
"name": "filmnodejsapi",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon api.js"
},
"dependencies": {
"body-parser": "~1.19.0",
"cors": "2.8.5",
"express": "~4.17.1",
"mssql": "^7.2.0"
},
"devDependencies": {
"nodemon": "^2.0.12"
},
"keywords": [],
"author": "",
"license": "ISC"
}
When i do npm start the error shows up and not getting connected to the database. dont know what is the issue
I am trying to use ES6 Modules to import Express. Although I added "type":"module" in my package.json. The error, SyntaxError: Cannot use import statement outside a module, still occurs. I am expecting an answer which does not require to convert into a .ejs extension since wanting to know what's wrong in my code rather than taking an alternative. Note: package.json & server.js are in the same directory.
package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "server.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.10.3",
"nodemon": "^2.0.4"
}
}
Server.js
import express from 'express';
const app = express()
const port = process.env.PORT || 9000
app.get('/', (req, res) => {
res.status(200).send('hello world');
})
app.listen(port, () => {
console.log(`Listening on localhost: ${port}`)
});
I'm trying to follow a tutorial for starting up my first NodeJS app, but I don't understand why I am getting this error. I'm attempting to connect a MongoDB database with the app, and obviously had to modify my Start.js file in order to do that... but the error says I'm missing that file completely. Here's my Start.js:
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${process.env.DATABASE}`);
})
.on('error', (err) => {
console.log(`Connection error: ${err.message}`);
});
const app = require('./app');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I was told to create a .env file to place in the project folder as well, could this have something to do with it? Maybe the address to the database is incorrect? Any assistance would be greatly appreciated.
EDIT: Here's my package.json file
{
"name": "demo-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "nodemon ./start.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.3.0",
"mongoose": "^5.8.3",
"pug": "^2.0.4"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}