Я не могу ничего добавить и удалить в своей базе данных, и я думаю, что мое ядро верное
Это для проекта под управлением MariaDB 10.1.37, Apache 2.
Код:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = 3000;
const mysql = require('mysql');
function execSQLQuery(sqlQry, res){
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'usdb'
});
connection.query(sqlQry, function(error, results, fields){
if(error)
res.json(error);
else
res.json(results);
connection.end();
console.log('executou!')
})
}
//cofigurando body parser para pegar os POSTS mais tarde
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//definindo as rotas
const router = express.Router();
router.get('/',(req,res) => res.json({message: 'Funcionando!'}));
app.use('/',router);
router.get('/substances',(req, res) =>{
execSQLQuery('SELECT * FROM organicssubstances', res);
});
router.get('/substance/:id?', (req, res) =>{
let filter = '';
if(req.params.id) filter = ' WHERE id=' + parseInt(req.params.id);
execSQLQuery("SELECT * FROM organicssubstances"+filter, res);
});
router.get('/substance/:id', (req,res) =>{
execSQLQuery("DELETE FROM organicssubstances WHERE id=" + parseInt(req.params.id), res);
});
router.get('/substances', (req,res) =>{
const substance = req.body.substring(0,150);
const formula = req.body.substring(0,150);
execSQLQuery(`INSERT INTO organicssubstances(substance, formula) VALUES('${substance}','${formula}')`, res);
});
//inicia o servidor
app.listen(port)
console.log('API Funcionando!')
Код PUT и DELETE:
router.get('/substance/:id', (req,res) =>{
execSQLQuery("DELETE FROM organicssubstances WHERE id=" + parseInt(req.params.id), res);
});
router.get('/substances', (req,res) =>{
const substance = req.body.substring(0,150);
const formula = req.body.substring(0,150);
execSQLQuery(`INSERT INTO organicssubstances(substance, formula) VALUES('${substance}','${formula}')`, res);
});
Я вижу этот код на сайте и только адаптирован для моего использования, но не работает.
https://i.imgur.com/cDyyio4.png
https://i.imgur.com/y5zruZG.png