node js rest api creation not connecting to sql server - node.js

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

Related

yarn workspace not update the local package (making eslint plugin)

Problem
I'm making custom eslint plugin referencing working with plugins and generator-eslint. Then I make a monorepo using yarn workspace and turbo repo like following structure:
file structure
apps
service
.eslintrc.js
index.ts (written to throw eslint error)
package.json
packages
eslint-plugin-custom
lib
rules
func-prefix-matching.js
index.js
.eslintrc.js
package.json
package.json
turbo.json
The key files of it is:
apps/service/.eslintrc.js
module.exports = {
root: true,
extends: ['eslint:recommended'],
plugins: ['eslint-plugin-custom'],
env: {
node: true,
es6: true,
},
rules: {
"custom/func-prefix-matching": ['error']
}
};
apps/service/package.json
{
"name": "service",
"version": "0.0.0",
"private": true,
"scripts": {
"lint": "eslint ."
},
"dependencies": {},
"devDependencies": {
"eslint": "8.22.0",
"eslint-plugin-custom": "*",
"typescript": "^4.5.3"
}
}
packages/eslint-plugin-custom/lib/rules/func-prefix-matching.js
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const rulePrefix = ["is", "pre", "on", "post", "get", "set"];
const isValidName = (name, { prefix, exclude }) => {
const isValid = (prefix) => name.indexOf(prefix) === 0;
return exclude.some(isValid) || prefix.some(isValid);
};
/** #type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion', // `problem`, `suggestion`, or `layout`
docs: {
description: 'exmaple',
recommended: false,
url: null, // URL to the documentation page for this rule
},
fixable: null, // Or `code` or `whitespace`
schema: [], // Add a schema if the rule has options
messages: {
example: 'example',
},
},
create(context) {
const { options } = context;
const {include = [], exclude = [] } = options[0]||{};
return {
Identifier: (node) => {
if (node.parent.init && node.parent.init.type === 'ArrowFunctionExpression'
// You can add more checks here
) {
const { name } = node;
const allPrefix = [...include, ...rulePrefix].sort();
// Sorting is optional
if (!isValidName(name, { prefix: allPrefix, exclude })) {
context.report({
node,
messageId: `${name} should start with ${allPrefix.join(", ")}.`,
});
}
}
},
};
},
};
packages/eslint-plugin-custom/package.json
{
"name": "eslint-plugin-custom",
"version": "1.0.0",
"description": "ESLint plugin",
"keywords": [
"eslint",
"eslintplugin",
"eslint-plugin"
],
"author": "inflab",
"main": "./lib/index.js",
"exports": "./lib/index.js",
"files": [
"lib",
"README.md"
],
"scripts": {
"lint": "eslint .",
"test": "mocha tests --recursive --watch"
},
"dependencies": {
"requireindex": "^1.2.0"
},
"devDependencies": {
"eslint": "7.32.0",
"eslint-plugin-eslint-plugin": "^5.0.0",
"eslint-plugin-node": "^11.1.0",
"mocha": "^10.0.0"
},
"engines": {
"node": "^14.17.0 || ^16.0.0 || >= 18.0.0"
},
"peerDependencies": {
"eslint": ">=7"
},
"license": "ISC"
}
package.json
{
"name": "custom-lint",
"version": "0.0.0",
"private": true,
"workspaces": [
"apps/*",
"packages/*"
],
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev --parallel",
"lint": "turbo run lint",
"format": "prettier --write \"**/*.{ts,tsx,md}\"",
"test": "turbo run test"
},
"devDependencies": {
"prettier": "latest",
"turbo": "latest"
},
"engines": {
"node": ">=14.0.0"
},
"dependencies": {},
"packageManager": "yarn#1.22.19"
}
turbo.json
{
"$schema": "https://turborepo.org/schema.json",
"pipeline": {
"build": {},
"lint": {
"outputs": []
},
"dev": {
"cache": false
},
"test": {}
}
}
issue
Now, eslint make output:
[Error - 10:34:20 PM] TypeError: context.report() called with a messageId of 'function1 should start with get, is, on, post, pre, set.' which is not present in the 'messages' config: {
"example": "example"
}
Occurred while linting /custom-lint/apps/service/index.ts:1
So I edit code like:
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const rulePrefix = ["is", "pre", "on", "post", "get", "set"];
const isValidName = (name, { prefix, exclude }) => {
const isValid = (prefix) => name.indexOf(prefix) === 0;
return exclude.some(isValid) || prefix.some(isValid);
};
/** #type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
...
messages: {
messageId: 'message',
},
},
create(context) {
...
return {
Identifier: (node) => {
if (node.parent.init && node.parent.init.type === 'ArrowFunctionExpression'
// You can add more checks here
) {
const { name } = node;
const allPrefix = [...include, ...rulePrefix].sort();
// Sorting is optional
if (!isValidName(name, { prefix: allPrefix, exclude })) {
context.report({
node,
messageId: 'messageId',
});
}
}
},
};
},
};
Then yarn workspace automatically make symlink to the eslint-plugin-custom package and I can see the latest edited code in (project root)/node_modules/eslint-plugin-custom. But the same error is occurred.
[Error - 10:34:20 PM] TypeError: context.report() called with a messageId of 'function1 should start with get, is, on, post, pre, set.' which is not present in the 'messages' config: {
"example": "example"
}
Occurred while linting /custom-lint/apps/service/index.ts:1
what I tried
It looks like cache problem, so I run yarn cache clean. But not work
I change the plugin version like
packages/eslint-plugin-custom/package.json
{
"name": "eslint-plugin-custom",
"version": "1.0.1",
...
}
apps/service/package.json
{
"name": "service",
"version": "0.0.0",
"private": true,
"scripts": {
"lint": "eslint ."
},
"dependencies": {},
"devDependencies": {
"eslint": "8.22.0",
"eslint-plugin-custom": "1.0.1",
"typescript": "^4.5.3"
}
}
to match exact version, but it does not work.
removing node_modules dirs and re-install, not work.
what I expect
I expect
the plugin work correctly
to see the output of eslint change when I edit plugin code
Is there any help... :(

I have problem with my server.js either is npx or the problems below i cannot start my application

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

Can not Find module in "index.js"

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",
...

Can't connect pgadmin to the server

I'm trying to connect my server (based on node.js) with db from pgAdmin.<>
However I keep getting '${PORT}', instead of PORT's value in env file :
pgAdmin part:
index.js file:
require('dotenv').config()
const express = require ('express')
const sequelize = require('./db')
const PORT = process.env.PORT || 5000
const app = express()
const start = async () => {
try {
await sequelize.authenticate()
await sequelize.sync()
app.listen(PORT,()=>console.log('Server started on port ${PORT}'))
} catch (e) {
console.log(e)
}
}
start()
db.js:
const {Sequelize} = require('sequelize')
module.exports = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect:'postgres',
host: process.env.DB_HOST,
port: process.env.DB_PORT
}
)
.env file:
PORT=7000
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD='Ondj8_oP1sw'
DB_HOST=localhost
DB_PORT=5432
package.json:
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"pg": "^8.8.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.21.4"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
The actual connection should be fine, yet your console.log should look like console.log(`Server started on port ${PORT}`), use back ticks `` if you want to console.log a variable.

When I put require('nodemailer'); at begging of code, all of the code doesn't work

(I already Installed nodemailer)
"name": "APIName",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}
Hello I have an error before initialization, however I don't understand what's wrong (even I searched google). can anyone tell me what's wrong? Error also occurs to content variable . (Cannot access 'content' before initialization) Thanks you.
register.js:114 Uncaught (in promise) ReferenceError: Cannot access 'nodemailer' before initialization
at send (register.js:114)
at HTMLButtonElement.register (register.js:128)
const emailInfo = {
host: "smtp.mailtrap.io",
port: 2525,
secure: false,
auth: {
"user": "Don't try to see :P",
"pass": "Do not try to see :P",
}
};
const content = {
from: "aewr#naver.com",
to: "myemail#inbox.mailtrap.io",
subject: "YESS",
text: "HI"
}
async function send(data) {
nodemailer.createTransport(emailInfo).sendMail(data, function (error, info) { // line 114 ERROR POINT
if (error) {
console.log(error);
} else {
console.log(info);
return info.response;
}
});
}
async function register() {
if (!(checkNickName() && checkEmailCorrect() && checkPw() && comparePw())) return;
console.log("WORK") // check if it works to here
await send(content); // line 228 ERROR POINT
}```

Resources