nodejs require 找不到名称
nodejs require cannot find name
我正在尝试从导入中 return connection
的一个实例。
const express = require('express')
const bodyParser = require('body-parser')
require("dotenv").config();
db = require('./services/db_service').db_connection() <---- here
var app = express();
app.use(bodyParser.json());
app.get('/customers' , (req, res) => {
db.query('SELECT * FROM customers', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
})
} );
app.listen(process.env.PORT, function () {
console.log(`Example app listening on port ${process.env.PORT}!`)
})
在 /services/db_service.ts
文件中:
export const db_connection = function () {
const { HOST, USER, PASSWORD, DATABASE } = process.env
var mysql = require('mysql');
var con = mysql.createConnection({
host: HOST,
user: USER,
password: PASSWORD,
database: DATABASE,
multipleStatements: true
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
return con; <--- return this
}
但是我得到这个错误:
index.ts:6:1 - error TS2304: Cannot find name 'db'.
db = require('./services/db_service').db_connection()
试试
const db = require('./services/db_service').db_connection()
此外,要优化与数据库的新连接,请参阅您正在使用的 ORM 文档
我正在尝试从导入中 return connection
的一个实例。
const express = require('express')
const bodyParser = require('body-parser')
require("dotenv").config();
db = require('./services/db_service').db_connection() <---- here
var app = express();
app.use(bodyParser.json());
app.get('/customers' , (req, res) => {
db.query('SELECT * FROM customers', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
})
} );
app.listen(process.env.PORT, function () {
console.log(`Example app listening on port ${process.env.PORT}!`)
})
在 /services/db_service.ts
文件中:
export const db_connection = function () {
const { HOST, USER, PASSWORD, DATABASE } = process.env
var mysql = require('mysql');
var con = mysql.createConnection({
host: HOST,
user: USER,
password: PASSWORD,
database: DATABASE,
multipleStatements: true
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
return con; <--- return this
}
但是我得到这个错误:
index.ts:6:1 - error TS2304: Cannot find name 'db'.
db = require('./services/db_service').db_connection()
试试
const db = require('./services/db_service').db_connection()
此外,要优化与数据库的新连接,请参阅您正在使用的 ORM 文档