这是我的代码我正在尝试用mysql制作api,数据库中的表已经插入了用户名和密码
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'fsoc',
database: 'nodesql'
});
//connection
conn.connect((err) => {
if (err) {
throw err;
}
console.log('Mysql Connected');
});
//Select query
app.get('/show', (req, res) => {
let sql = 'SELECT * from users';
conn.query(sql, (err, result) => {
if (err) throw err;
res.send(result[0]);
});
console.log(req.body);
});
app.listen(3000,()=>{
console.log('check on 3000');
})
虽然在邮递员中它显示用户名和密码的JSON数据为
{
"id": 2,
"username": "ujju",
"password": "fsoc11"
}
答案 0 :(得分:1)
您必须将get
方法替换为post
才能使req.body
填充已发布的数据,同样在邮递员中您必须使用发布请求并提供一些表单数据:
app.post('/show', (req, res) => {
console.log(req.body); //log posted data
let sql = 'SELECT * from users';
conn.query(sql, (err, result) => {
if (err) throw err;
res.send(result[0]);
});
});