error message

DB에 접속하지 못하여 발생한 에러

 확인해본 것들

  1. Mysql port number ( 3306 이 아닌지 확인 )
  2. database 이름
  3. GUI로 mysql 접속 가능한지

connect ECONNREFUSED ::1:3306 문구에서

 
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost', // <--- 에러일으킴
  dialect: 'mysql'
});

 

host 수정!!

const sequelize = new Sequelize('database', 'username', 'password', {
  host: '127.0.0.1', // <--- 해결
  dialect: 'mysql'
});

https://sequelize.org/

 

Sequelize

Sequelize is a modern TypeScript and Node.js ORM for Oracle, Postgres, MySQL, MariaDB, SQLite and SQL Server, and more. Featuring solid transaction support, relations, eager and lazy loading, read replication and more.

sequelize.org

1. 라이브러리 설치

npm i sequelize
npm i mysql2

2. DB 연결 (app.js)

const express = require('express');
const app = express();
const port = 3000;
const { Sequelize } = require('sequelize');

// database, username, password는 자신의 DB에 맞는 값을 입력해야 한다. 
// username: root (주로)
// password : 설정하지 않았으면 null 과 '' 중에 하나 입력
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

app.get('/', (req, res) => {
  res.send('Hello World!');
})

app.listen(port, async () => {
  try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
  console.log(`서버가 실행됩니다. http://localhost:${port}`);
})

 

객체 생성방법

// 직접입력
let person = {
  name: "아무개",
  age: 30,
  gender: "남자"
};

//함수 사용
function makePersonObject(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
}

//속성? value 
console.log(person.name) // "아무개"

객체 메소드

// values
const values = Object.values(person); // ["아무개", 30, "남자"]

// keys
const keys = Object.keys(person); // ["name", "age", "gender"]

// entire

console.log( Object.entire(persion)
// Array [Array ["name", "아무개"], Array ["age", 30], Array ["gender", "남자"]]

// assign
const newPerson = Object.assign({}, person, { name: "홍길동" }); // 이름만 바뀌어서 복사

객체 비교

console.log(person === newPerson); // false , object 끼리 연사자 이용해서 비교 불가
console.log(JSON.stringify(person) === JSON.stringify(newPerson)) // true,JSON.stringify 이용해서 비교 가능

객체 병합

const mergedPerson = {...person, ...newPerson};

'프로그래밍 > JavaScript' 카테고리의 다른 글

[ JS ] 정렬 sort( )  (0) 2024.04.13
[JS] call, apply, bind  (0) 2024.03.06
배열 뒤집기  (0) 2023.07.30
array.reduce()  (0) 2023.07.30
Class  (0) 2023.07.13
const arr = [1,2,3];

let arrReverse = [];

for ( let i =arr.length -1; i >=0 ; i --){
	arrReverse.push(arr[i]);
 }
 
 const arrReverse2 = arr.reverse(); // 원본 배열도 순서가 뒤집힌다.
 
 const arrReverse3 = [...arr].reverse(); // 원본배열 복사후 배열순서 바꾸기

Spread operator(스프레드 연산자,  ... )

=> 배열/객체 를 펼쳐서 각 요소를 분리 후, 매개변수 목록으로 만든 다음에  매개변수를 새로운 배열/객체 에 할당함.

const arr = [1,2,3];
const obj = { a: 1, b: 2, c: 3 };
// copy
let arrayCopy2 = array.assign([], arr);
let objectCopy2 = Object.assign({}, obj);
// spread operator
const arrayCopy = [...arr] // array copy
cosnt objectCopy = {...obj} // object copy

const str = "hello"
const strStread = [...str] // ["h", "e", "l", "l", "o"]

=> 복사를 한 배열/객체 안의 요소는 원본과 같다.

=> 하지만, 원본의 값이 바뀌어도 복사된 배열/객체 의 값은 변하지 않는다. ( python 에서 copy.deepcopy 와 같음)

 

참고 :https://ko.javascript.info/rest-parameters-spread#spread-syntax

 

나머지 매개변수와 스프레드 문법

 

ko.javascript.info

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

[JS] call, apply, bind  (0) 2024.03.06
객체(Object), 객체 메소드  (0) 2023.08.03
array.reduce()  (0) 2023.07.30
Class  (0) 2023.07.13
Functions - arrow, map, filter  (0) 2023.07.12

array.reduce(callback, initialValue) 로 구성

 

callback - > (accumulator, currentValue, currentIndex, array)

initalValue (option)

를 구성해서 array 에있는 값을 모두 더 할때 사용된다.

 

const arr = [1,2,3];

const result1 = arr.reduce((acc,value) => acc += value); //6

const result2 = arr.reduce((acc,value) => {acc += value}, 10); //16
const result2_1 = arr.reduce((acc,value) => acc += value, 10); //16

 

 

(참고) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

 

Array.prototype.reduce() - JavaScript | MDN

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the a

developer.mozilla.org

 

'프로그래밍 > JavaScript' 카테고리의 다른 글

객체(Object), 객체 메소드  (0) 2023.08.03
배열 뒤집기  (0) 2023.07.30
Class  (0) 2023.07.13
Functions - arrow, map, filter  (0) 2023.07.12
콜백(callback)함수  (0) 2023.07.12

+ Recent posts