vscode debugger unexpected toke 'import' - mysql

I am new to nodejs and vscode...... I have two files: entry.js and /utils/database.js.
When I run node entry.js I get the little logging that I expect(SSSS). I would like to run this in debug mode so that I can build on it but when I click on the "Run" in debug on the left side I get:
SyntaxError: Unexpected token import
System: Ubuntu 18.04
Editor: Visual Studio Code version 1.45.1
node --version: v13.11.0
npm --version: 6.13.7
package.json:
{
"type": "module",
"name": "node_load_test",
"version": "1.0.0",
"description": "",
"main": "entry.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"mysql": "^2.18.1"
}
}
launch.json:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch root Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/entry.js"
},
{
"type": "node",
"request": "launch",
"name": "Launch 6 Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/6/entry.js"
}
]
}
utils/database.js:
import mysql from "mysql";
export const pool = mysql.createPool({
connectionLimit: 100,
host: "localhost",
user: "root",
password: "password",
database: "no_replicate",
});
entry.js:
"use strict";
import { pool } from "./utils/database.js";
pool.end(function (err) {
if (err) {
return console.log("error:" + err.message);
}
console.log("Close the database connection.");
});
pool.getConnection(function (err, connection) {
// execute query
// ...
console.log("SSSS");
});
Any help would make my day. Thanks

in utils/database.js:
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 100,
host: "localhost",
user: "root",
password: "password",
database: "no_replicate",
});
module.exports = pool
in entry.js
const pool = require('./utils/database.js');
pool.end(function (err) {
if (err) {
return console.log("error:" + err.message);
}
console.log("Close the database connection.");
});
pool.getConnection(function (err, connection) {
// execute query
// ...
console.log("SSSS");
});
and in Nodejs we import like with require('package-name')

Related

Unable to connect to mySQL from Node.js

I am able to connect via the mySQL shell, but when I try from VS Code Nodemon crashes and i get the error.
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlMessage: "Access denied for user 'root'#'localhost' (using password: YES)",
sqlState: '28000',
fatal: true
My environment variable path is set up.
I have run... ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY '123456'
I have set up a new user, granted them full permissions and tried to connect to that user but still denied access.
//server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
var mysql = require('mysql');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456'
});
db.connect((err) => {
if(err){
console.log(err);
} else {
console.log('Connected');
}
})
app.listen('8000', () => console.log("Server running on port 8000"));```
package.json
{
"name": "mern-prac-2-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"mysql": "^2.18.1",
"nodemon": "^2.0.20"
}
}
Thanks!
(edited)
Based on Juans Answer I have changed to this...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const {Sequelize} = require('sequelize');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const sequelize = new Sequelize('fake_company', 'root', '123456', {
host: 'localhost',
dialect: 'mysql',
});
const tryConnection = async () => {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
tryConnection();
app.listen('8000', () => console.log("Server running on port 8000"));
And am having the error ...
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'#'localhost' (using password: YES)",
sql: undefined
I connect NodeJS con MySQL/MariaDB using sequelize package, this code is with typescript, you must change imports to require.
import { Sequelize } from 'sequelize';
// -----------------------------------------------------
const sequelize = new Sequelize('node', 'username', 'your-password', {
host: 'localhost',
dialect: 'mysql',
// logging: false
/* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
});
// -----------------------------------------------------
export default sequelize;
//------------------------------------------------------
// Then in the server I have this code.
import express, { Application } from 'express';
import cors from "cors";
import userRoutes from '../routes/usuario.mjs';
import sequelize from '../db/connection.mjs';
class Server {
private app: Application;
private port: string;
private apiPath ={
usuarios: '/api/usuarios'
}
// -----------------------------------------------------
constructor(){
this.app = express();
this.port = process.env.PORT || '8000';
// connect to DB
this.dbConnection();
// ...
}
// -----------------------------------------------------
// Connect with DB
async dbConnection(){
try {
await sequelize.authenticate();
console.log('Database is connected.');
} catch (error: any) {
throw new Error( error.message );
}
}
}
It works porperly for my.
If you want to use sequelize, I think you can create the perfect configuration with sequelize init commands. Sequelize gives you a config file in a configuration folder like below. You have to define a database for sequelize don't forget that.
Firstly you have to install npm install --save-dev sequelize-cli for your cli commands.Then you can use sequelize init command.
{
"development": {
"username": "root",
"password": "123456",
"database": "your db",
"host": "127.0.0.1",
"dialect": "mysql",
"query": {
"raw": true
},
"options": {
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
},
{
"development": {
"username": "root",
"password": "123124",
"database": "yourDB",
"host": "127.0.0.1",
"dialect": "mysql",
"query": {
"raw": true
},
"options": {
"pool": {
"max": 5,
"min": 0,
"acquire": 30000,
"idle": 10000
}
}
},
I think creating a new user and giving it privilege will help. The root user might need root access or administrative access. And node doesn't have a root access.

Typeorm pool doesn't exist in replication

typegraphql, typeorm, Mysql with master slave replication.
I have configured mysql with master and slave databases with separate instances and its working fine. I have encounter an error
while connecting via typeorm. Here's my ormconfig.json
{
"type": "mysql",
"logging": true,
"replication": {
"master":
{
"host": "192.168.0.250",
"port": 3306,
"username": "root",
"password": "test#123",
"database": "master",
"synchronize": true,
"extra": {
"connectionLimit": 5
}
}
,
"slaves": [
{
"host": "192.168.0.175",
"port": 3306,
"username": "root",
"password": "test#123",
"database": "master",
"synchronize": true,
"extra": {
"connectionLimit": 5
}
}
]
},
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
My index.ts file with database connection as
import { gqSchema } from './schema';
import "reflect-metadata";
import { createConnection } from "typeorm";
import { ApolloServer } from "apollo-server";
async function main() {
await createConnection().then(async(res) => {
console.log(res)
console.log("Database Connected")
const schema = await gqSchema()
const server = new ApolloServer({
schema,
context: ({ req }: any) => ({ req })
})
await server.listen(4000)
console.log("Server has started!")
}).catch(err => {
console.log("err", err)
})
}
main();
And my resolver.ts file
#Resolver()
export class UserResolver {
/**
* query
*/
#Authorized()
#Query(() => User)
async hello(
#Arg("firstName") firstName: string,
): Promise<User | undefined > {
const slaveQueryRunner = getConnection().createQueryRunner("slave");
try {
const connection = getConnection().getRepository(User);
const usersList = await connection.createQueryBuilder()
.from(User, "user")
.setQueryRunner(slaveQueryRunner)
.where("user.firstName = ", {firstName})
.getOne();
console.log(usersList)
} finally {
slaveQueryRunner.release();
}
}
}

Webpack, babelrc dynamic import not working

I spent quite some time trying to figure this out myself but here I am, with no more options to consider than to reach out to the community for some guidance.
I am trying to do something very simple in principle, dynamically import a component with WebPack, using ES6 modules and babelrc.
I have the following app architecture:
-root
-- root/.webpack.dev.js
-- root/.webpack.prod.js
-- root/.babelrc
-- root/package.json
-- root/node_modules/
-- root/dist/
-- root/src/
--- root/src/index.js
--- root/src/modules/
--- root/src/modules/module1.js
--- root/src/modules/module2.js
--- root/src/modules/module3.js
--- root/src/modules/module4.js
--- root/src/modules/module5.js
In my module1.js (not the real name) I am using the following code to dynamically import module2.js:
async function load(configObject) {
const {
init,
requestPermissions
} = await import( /* webpackChunkName: "chunkname" */ `./module2.js`)
init(configObject)
_namespace.requestPermissions = requestPermissions;
}
My .babelrc file:
{
"presets": [
["#babel/preset-env", {
"targets": "> 0.25%, not dead"
}]
],
"plugins": ["#babel/plugin-syntax-dynamic-import",
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
],
"comments": true
}
// "#babel/preset-env"
My Webpack config:
const path = require('path');
const webpack = require('webpack')
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin
const WorkboxPlugin = require('workbox-webpack-plugin');
const {
InjectManifest
} = require('workbox-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
entry: {
lib: "./src/index.js"
},
mode: 'development',
module: {
rules: [{
test: /\.js$/,
use: [{
loader: "babel-loader"
}],
exclude: /node_modules/
}]
},
optimization: {
minimizer: [new TerserPlugin({
test: /\.js(\?.*)?$/i,
parallel: true,
cache: true,
terserOptions: {
ecma: 8,
warnings: false,
parse: {
ecma: 8,
},
compress: {
warnings: false,
comparisons: false,
},
mangle: {
safari10: true,
},
module: false,
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
toplevel: false,
nameCache: null,
ie8: false,
keep_classnames: undefined,
keep_fnames: false,
safari10: false,
},
})],
},
output: {
filename: '[name].js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: "/"
},
devServer: {
contentBase: "dist",
compress: true,
stats: {
colors: true
},
overlay: true
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development'),
'API_URL': JSON.stringify('ENDPOINT')
}
}),
new BundleAnalyzerPlugin({
generateStatsFile: true
}),
new WorkboxPlugin.GenerateSW({
"swDest": "firebase-messaging-sw.js",
}),
new InjectManifest({
"swSrc": path.join('src', 'firebase-messaging-sw.js')
})
]
};
My package.json:
{
"name": "refactor",
"version": "1.0.0",
"description": "",
"main": "backuprefacto.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "NODE_ENV=production webpack --config=webpack.prod.js",
"build:dev": "webpack --config=webpack.dev.js",
"start": "webpack-dev-server --config=webpack.dev.js"
},
"keywords": [],
"private": true,
"license": "ISC",
"devDependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.5.5",
"babel-loader": "^8.0.6",
"babel-minify": "^0.5.1",
"babel-minify-webpack-plugin": "^0.3.1",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"terser-webpack-plugin": "^1.4.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.39.2",
"webpack-bundle-analyzer": "^3.4.1",
"webpack-cli": "^3.3.7",
"webpack-dev-server": "^3.8.0",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"#babel/core": "^7.5.5",
"#babel/plugin-transform-runtime": "^7.5.5",
"#babel/runtime": "^7.5.5",
"firebase": "^6.4.0",
"save": "^2.4.0"
}
}
I have checked all my modules, none of them expect for module1.js are calling module2.js.
I have also explored the option of webpack comments being deleted by babel and therefore added a comments: true to make sure the webpackChunkName is not being deleted but in the end, the only thing that gets built is my lib.js, not the lib.bundle.js that I expect.
I have also tried to remove all the TerserPlugin bit to check if that could have the same impact but nothing changed there.
In the need, what I am looking for is simply to have the module2.js loaded whenever it is invoked, and I therefore expect a new network request to materialise this.
Well, it turns out that if you want to use dynamic imports you need to make sure first that you are not importing at all the module at the top....
In module1.js I was importing twice, once at the top, the "regular way", once the dynamic way which was obviously leading to module2.js being consistently loaded.
I resolve my problem by modify .babelrc, modules: false
["#babel/preset-env", {
"loose": true,
"useBuiltIns": "usage",
"corejs": 3,
"modules": false
}],

How can we get data from mysql database in angular 7 application by using node.js and display it on angular component html page

I have tried every thing but i cant under stand how to reach my goal.
Now my main goal is that i want to get data from mysql database and then access this information in angular component which is page-one.component.ts file. Now i can connect to the database and can get the data from database in server.js file. but i cant understand how to get the information in angular component. The method i have tried so far is that i include the server.js file in angular.json file and then include the function "get_data" (get_data function fetch data from database in server.js file) in my page-one.component.ts file and then i call the function in page-one.component.ts file. The function is called, but the problem is that i got error in server.js file that " Cannot read property 'createConnection' of undefined". This error stops me from getting the information from database. but when i call this get_data function in server.js file i got the database information and i can print the information in console.
Can any one give me the solution please.
I think the error is because of the context of variable.
but please guide me.
My server.js file code.
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
var mysql = require('mysql');
var dbconfig = {
host: "localhost",
user: "root",
password: "",
database: "mydb"
}
var con = mysql.createConnection(dbconfig);
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
get_data();
function get_data(){
console.log("function called");
var con = this.mysql.createConnection(dbconfig); ===> GOT ERROR HERE
con.query("SELECT * FROM teacher", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
server.listen(port, () => {
console.log(`server running on port ${port} `);
})
My page-one.component.ts file code.
import { Component, OnInit } from '#angular/core';
import { Http } from '#angular/http';
declare function get_data(): any;
#Component({
selector: 'app-page-one',
templateUrl: './page-one.component.html',
styleUrls: ['./page-one.component.css']
})
export class PageOneComponent implements OnInit {
constructor(private http: Http) { }
ngOnInit() {
get_data();
}
}
My angular.json file code.
{
"$schema": "./node_modules/#angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"myapp": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"prefix": "app",
"schematics": {},
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/myapp",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts":
[
"server.js" ===> INCULDED THE SERVER.JS FILe HERE
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
},
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "myapp:build"
},
"configurations": {
"production": {
"browserTarget": "myapp:build:production"
}
}
},
"extract-i18n": {
"builder": "#angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "myapp:build"
}
},
"test": {
"builder": "#angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.css"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"myapp-e2e": {
"root": "e2e/",
"projectType": "application",
"architect": {
"e2e": {
"builder": "#angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "myapp:serve"
},
"configurations": {
"production": {
"devServerTarget": "myapp:serve:production"
}
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": "e2e/tsconfig.e2e.json",
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"defaultProject": "myapp"
}
" Cannot read property 'createConnection' of undefined"
const mysql = require('mysql2');
const connection = mysql.createPool({
host: 'localhost',
user: '',
password: '',
database: '',
connectionLimit: 10,
queueLimit: 0
});
connection.promise((err) => {
if (err) throw err;
console.log('connected!');
});
module.exports = connection.promise();
app.get("/youroute", (req, res, next) => {
"use strict";
const getProduct = "SELECT * FROM yourtable";
database.query(getProduct, (err, rows, fields) => {
if (err) {
res.status(500).send({ error: 'Something failed!' })
};
res.status(200).json({
message: "",
product: rows,
});
});
});
Service for Angular
export interface You {
id: number,
title: string,
content: string
}
Get Method on Model Angular
getData() {
this.http.get<{message:string,name:Name[]}>("URL")
.subscribe(result =>{
console.log(result);
});
and in HTML make For Loop with NGFOR for display your data

Message.Create is not a function sequelize cli

I have installed mysql sequelize in my project then I creadted Message Model using sequelize command which create model and migration file .I also given the db credentials in config.json file.Now I am trying to insert record in my db but getting this error here is my model file
DO i need to make db connection explicitly or it auto picks the
credential from config.json file to make connection ?
models/messages.js
'use strict';
module.exports = (sequelize, DataTypes) => {
var Messages = sequelize.define('Messages', {
room: DataTypes.STRING,
nickname: DataTypes.STRING,
message: DataTypes.STRING,
receiver: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Messages;
};
here is config.json file
config/config.json
{
"development": {
"username": "root",
"password": "asad",
"database": "chat",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
and here is my server file to save record
app.js file
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
server.listen(4000);
var Messages=require('../models/Messages.js');
router.post('/', function(req, res, next) {
var a =req.body;
Messages.create(a).then(() => {
console.log('success ')
})
})
make sequelize connection instance and export it, please use config according to your environment
const sql = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: config.dialect,
pool: {
max: 5,
min: 0,
idle: 10000
},
});
module.export = sql;
In your app.js import sql instance and connect your db before starting your server.
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').createServer(app);
var sql = require(./sql);
sql.authenticate().then(()=>{
server.listen(4000);
});
var Messages= sql.import('../models/Messages.js');
router.post('/', function(req, res, next) {
var a =req.body;
Messages.create(a).then(() => {
console.log('success ')
})
})