我的问题是我正在尝试为我的项目添加编辑功能。我已将/edit
路由器添加到我的classroom.js文件中,然后我通过应用程序编辑该标志,并在控制台日志中获得POST /classroom/edit 404 398.484 ms - 1355
。在浏览器控制台日志中,我得到:
App.js:32 POST http://localhost:3002/classroom/edit 404 (Not Found)
App.js:52 Error: Bad response from server
at App.js:40
React:App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
toggle: false,
toggleIdx: 0,
classroom: [],
flagreason: '',
msg: ''
};
this.eventHandler = this.eventHandler.bind(this);
this.logChange = this.logChange.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
logChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleEdit(event) {
event.preventDefault()
var data = {
flagreason: this.state.flagreason,
id: this.state.toggleIdx
}
fetch("/classroom/edit", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
console.log(data)
if (data === "success") {
this.setState({
msg: "Flag Reason has been edited."
});
console.log('Successful Update!');
}
}).catch(function(err) {
console.log(err)
});
}
eventHandler(event, idx) {
this.setState((prevState) => ({
toggle: !prevState.toggle,
toggleIdx: idx
})
);
}
componentDidMount() {
fetch("/classroom")
.then(res => res.json())
.then(classroom => this.setState({ classroom }))
}
render() {
return (
<div className="App">
<div className="wrapper">
<h1>Classroom</h1>
{this.state.classroom.map((classroom, idx) =>
<div className="child" key={classroom.id}>
<p className="detail">Child's Name: <span className={classroom.childflagged}>{classroom.childsname}</span> <i title={classroom.flagreason} className={'fa fa-flag flag' + classroom.childflagged}></i><i title={classroom.starreason} className={'fa fa-star star' + classroom.starstudent}></i></p>
<p className="detail">Parent's Phone Number: {classroom.parentsnumber}</p>
<div className="actionMenu">
<button className="flags" id={classroom.id} onClick={e => this.eventHandler(e, idx)}>Edit Flags</button>
<button className="results">View Results</button>
<button className="profile">View Profile</button>
</div>
<div className="actionForm">
<div>
<form id={"flagform" + classroom.id} className={(this.state.toggle && (this.state.toggleIdx === idx)) ? '' : 'hide'} onSubmit={this.handleEdit} method="post" autoComplete="no">
<input type="hidden" name="id" value={classroom.id} />
<input type="text" onChange={this.logChange} value={this.state.flagreason} name="flagreason" placeholder="Reason For Flag" />
<input type="submit" name="submit" value="Save Changes" />
</form>
</div>
</div>
</div>
)}
</div>
</div>
);
}
}
export default App;
快递:app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var classroom = require('./routes/classroom');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/classroom', classroom);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3001);
module.exports = app;
classroom.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 30,
host: 'localhost',
user: 'root',
password: 'password',
database: 'dbname'
});
/* GET Classroom listing. */
router.get('/', function(req, res, next) {
console.log('A Client Requested Data...');
pool.query('SELECT * FROM classroom ORDER BY childsname ASC', function(err, results) {
if (err) throw err
var array = [];
for(var i = 0, len = results.length; i < len; i++) {
array.push(results[i]);
}
res.json(array);
});
});
/* EDIT Child Flag */
router.get('/edit', function(req, res, next) {
console.log('A flag was edited...');
pool.query("UPDATE classroom SET flagreason = '"+req.body.flagreason+"' WHERE id = '"+req.body.id+"'", function (err, results, fields) {
if(err) throw err;
res.send(JSON.stringify(results));
});
});
module.exports = router;
任何人都可以帮助我,展示我需要改变的内容,然后解释为什么它不起作用所以我可以从错误中吸取教训吗?
答案 0 :(得分:3)
您需要更新服务器上classroom.js
文件的一部分才能使用post方法:
router.post('/edit', function(req, res, next) {
console.log('A flag was edited...');
pool.query("UPDATE classroom SET flagreason = '"+req.body.flagreason+"' WHERE id = '"+req.body.id+"'", function (err, results, fields) {
if(err) throw err;
res.send(JSON.stringify(results));
});
});
目前它正在等待GET请求并且您正在发送POST,因此它不知道如何处理它。其余的应该没问题。
答案 1 :(得分:2)
根据提供的代码,似乎有2个问题导致404.第一个是在您的反应代码中您正在发出get
请求,但路由为/classroom/edit
第二个问题是,在您的反应代码中,您尝试访问/edit
,但根据提供的代码,它应该只是post
。
<强>更新强>
如果提供了额外的代码,问题似乎是因为您试图将get
转换为/classroom/edit
路线。
反应代码中的路由实际上应该是post
,路由处理程序应该更改为{{1}}。