简体   繁体   中英

Why does using then() callback in ExpressJS after a promise giving me an Error?

I'm new to NodeJS and ExpressJS. I'm trying to execute a simple Database query.

db.execute('SELECT * FROM restaurant').then().catch()

I'm getting this error :

db.execute('SELECT * FROM restaurant').then().catch() ^

TypeError: Cannot read property 'then' of undefined

I'm using MySQL Database running on phpMyAdmin. This is my Database Snapshot.

在此处输入图片说明

I've checked my database, it is connected. Below is my code in App.js!

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const admin = require('./routes/admin');
const shop = require('./routes/shop');
const db = require('./config/db');

const app = express();
app.use(bodyParser.urlencoded({extended:false}))

app.use('/admin',admin);
app.use('/shop',shop)

db.execute('SELECT * FROM restaurant').then().catch()

app.get('/', (req,res) =>{
res.status(200).send('<h3>Front page</h3>')
});


app.get('*', (req,res) =>{
res.status(404).send('<h1>File not found</h1>')
});

const port = process.env.PORT || 5000;
app.listen(port);

console.log('App is listening on port ' + port);

I want the names of the restaurant to get display on the browser.

Below is config/db file:

var mysql = require('mysql2');
var db = mysql.createPool({
host : 'localhost',
user: 'root',
database:'pos',
password:''
});

module.exports=db 

You need to export the promisified version of your pool in your config file like this:

var mysql = require('mysql2');
var db = mysql.createPool({
   host : 'localhost',
   user: 'root',
   database:'pos',
   password:''
});

module.exports=db.promise()

For more info, check the mysql2 docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM