[英]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.我可以通过 mySQL shell 进行连接,但是当我尝试从 VS Code Nodemon 崩溃时,我得到了错误。
code: 'ER_ACCESS_DENIED_ERROR', errno: 1045, sqlMessage: "Access denied for user 'root'@'localhost' (using password: YES)", sqlState: '28000', fatal: true代码:'ER_ACCESS_DENIED_ERROR',错误号:1045,sqlMessage:“用户'root'@'localhost'的访问被拒绝(使用密码:是)”,sqlState:'28000',致命:真
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.
我已经运行... ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456' 我已经设置了一个新用户,授予他们完全权限并尝试连接到该用户但仍然被拒绝访问。
//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.我使用 sequelize package 连接 NodeJS con MySQL/MariaDB,此代码是 typescript,您必须将导入更改为 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,我认为你可以使用 sequelize init 命令创建完美的配置。 Sequelize gives you a config file in a configuration folder like below.
Sequelize 在配置文件夹中为您提供配置文件,如下所示。 You have to define a database for sequelize don't forget that.
您必须为 sequelize 定义一个数据库,不要忘记这一点。
Firstly you have to install npm install --save-dev sequelize-cli for your cli commands.Then you can use sequelize init command.首先,您必须为您的 cli 命令安装 npm install --save-dev sequelize-cli。然后您可以使用 sequelize init 命令。
{
"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.
并且节点没有根访问权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.