[英]Creating dynamic link by requesting data from front-end in Node.js and Express.js
[英]Using axios to delete the row from mysql db.React as front end with node.js and express.js as backend
我正在嘗試使用 axios 和 React.js 作為前端,node.js 和 express.js 作為后端,從 mysql 數據庫中刪除該行。 當我單擊刪除按鈕時,兩個請求作為發送。 一個什么都不顯示,另一個在 DevTools 中拋出這個。
“無法刪除/員工”
它也沒有在終端中顯示任何console.log
語句。
以下是刪除路線有問題的路線代碼
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const port = process.env.PORT || 3301;
var mysql = require("mysql");
app.use(cors());
const SELECT_ALL_USER_QUERY = 'SELECT * FROM employees';
const DELETE_QUERY = 'Delete from employees where id =';
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
var con = mysql.createConnection({
host: 'localhost',
user:'root',
password:"password",
database:'People'
});
con.connect(function (err){
if(err) {
console.log("Error Conneting To DB",err)
} else {
console.log("Connection Established");
}
});
//get Requets
app.get('/employees', (req, res) => {
con.query(SELECT_ALL_USER_QUERY, (err, result) => {
if(err) {
res.send(err);
} else {
let obj ={
data : result
}
console.log(obj);
res.send(result);
}
})
});
//Post Request
app.post('/employees',(req,resp)=>{
let data = {name:req.body.name , surname:req.body.surname, id:req.body.id};
let sql_query = "INSERT INTO employees SET ?"
console.log("DAATA UPLOADED")
let query = con.query(sql_query,data,(err,resp)=>{
if(err) {
console.log(err);
}
});
});
//Delete Request
// app.delete('/employees',(req,resp)=>{
// // DEBUG:
// let data = {id:req.body.id};
// let sql_query = "Delete from employees where id = ?"
// let query = con.query(sql_query,data,(err,resp)=>{
// if(err){
// console.log(err);
// }
// else {
// console.log(resp);
// }
// })
// })
// app.delete('/employees', function(req, res){
// console.log(con.query('DELETE FROM employees WHERE id =' + req.body.id));
// //con.query('DELETE FROM employees WHERE id ='+req.body.id, function(err, results){
// // if(err) throw err;
// // });
//
// // req.flash('success', 'Project Deleted');
// // res.location('/admin');
// // res.redirect('/admin');
// });
app.delete("/employees/:id", (req, res) => {
console.log("Request",req.params.id);
let { ID } = req.params.id;
let sql = `DELETE FROM employees WHERE ID = ${req.params.id}`;
console.log("HI",sql);
// delete a row with id = req.params.id
conn.query(sql, (error, results, fields) => {
if (error) return console.error("ERROR HI",error.message);
res.status(200).send(results);
console.log("Deleted Row(s):", results.affectedRows);
});
});
app.listen(4000, () => {
console.log('server running on port 4000')
})
module.exports = app;
對於 ReactJs 有一個 function deleteName
其中寫入使用 axios 的刪除調用。 代碼如下:
import React from 'react';
import './App.css';
import axios from 'axios';
class App extends React.Component {
constructor(props){
super(props);
this.onNameChange = this.onNameChange.bind(this);
this.onSurnameChange = this.onSurnameChange.bind(this);
this.onIdChange = this.onIdChange.bind(this);
this.editName = this.editName.bind(this);
this.state = {
data:'',
name:'',
surname:'',
id:''
}
}
componentDidMount() {
axios.get('http://localhost:4000/employees').then((response,err)=> {
if(err) {
console.log('err');
}
this.setState((prevstate) =>
({
data: response.data
})
);
})
}
handleSumbit(e){
axios.post('http://localhost:4000/employees',{
name: this.state.name,
surname: this.state.surname,
id:this.state.id,
}).then((response,err)=>{
if(err) {
console.log("Error While Posting Data",err);
}
console.log("RESPONSE FROM POST",response);
})
}
onNameChange(e){
this.setState({
name:e.target.value
});
}
onSurnameChange(e) {
this.setState({
surname:e.target.value
})
}
onIdChange(e){
this.setState({
id:e.target.value
});
}
editName(e,firstname,lastname,id){
this.setState({
name:firstname,
surname:lastname,
id:id
});
}
deleteName(e,value) {
axios.delete('http://localhost:4000/delete/' + value).then((response) => {
// this only runs on success
console.log("RESPONSE FROM POST", response.data);
}, (err) => {
// this only runs on error
console.log("Error While Posting Data", err);
});
}
}
render() {
const {data} = this.state;
return (
<div className="container">
<div>
<label className="">Name</label>
<input type="text" name="" value={this.state.name} onChange={(e)=>this.onNameChange(e)}/>
</div>
<div>
<label className="">Surname</label>
<input type="text" name="" value={this.state.surname} onChange={(e)=>this.onSurnameChange(e)}/>
</div>
<div>
<label className=""> YOUR ID </label>
<input type="number" name="" value={this.state.id} onChange={(e)=>this.onIdChange(e)}/>
</div>
<div>
<button type="button" onClick={(e)=> this.handleSumbit(e)}>Sumbit</button>
</div>
<div className="main-container">
<h1>Name</h1>
{
data && data.map((data,key) => {
return(
<React.Fragment>
<div className="child">
{data.name}
<button onClick={(e)=> this.editName(e,data.name,data.surname,data.id)}>Edit</button>
<button onClick={(e)=> this.deleteName(e,data.id)}>Delete</button>
</div>
</React.Fragment>
)
})
}
</div>
</div>
)
}
}
export default App;
錯誤“Cannot DELETE /employees”表示名為/employees
的路由不存在。 您需要調用路由/delete/:id
。
另一方面,我注意到您沒有正確處理 axios 中的錯誤。 .then
function 接受兩個回調,第一個在成功時執行,另一個在錯誤時執行。
總的來說,這兩件事結合起來,試着這樣做:
axios.delete('http://localhost:4000/delete/' + value).then((response) => {
// this only runs on success
console.log("RESPONSE FROM POST", response.data);
}, (err) => {
// this only runs on error
console.log("Error While Posting Data", err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.