首先,我想為一個很長的帖子道歉。我是一個初學者,這是一種我什至不確定如何用谷歌搜索的行為。我會盡力解釋最好的方法。
我正在使用 Node、Express、React 和 Mongoose 構建一個簡單的 CRUD 應用程式。我從后端開始,繼續向前端。一旦我將前端與后端連接起來,我就注意到了一個不尋常的行為。例如,這是我的postEditStudent控制器:
exports.postEditStudent = (req, res, next) => {
console.log(req.params)
const id = req.params.id;
console.log('this is body', req.body)
Student.findByIdAndUpdate(mongoose.Types.ObjectId(id), {firstName : req.body.firstName, lastName : req.body.lastName})
.then((stud) => {
console.log('EDIT THIS GUY', stud);
return res.status(200).redirect('/')
})
.catch(err => console.log(err));
}
現在,要到達那里,我們正在使用路由器:
const express = require('express');
const classController = require('../controllers/classController');
const router = express.Router();
router.get('/update/:id', classController.getEditStudent);
router.patch('/update/:id', classController.postEditStudent);
至于我的 server.js 頁面,它是這樣設定的:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors())
const classRoutes = require('./routes/class-routes');
const errorController = require('./controllers/error')
const MONGODB_URI = "mongodb srv://this is a mongoose database path"
app.use('/teacher', authRoutes);
app.use('/class', classRoutes);
app.get('/', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
next()
})
app.use(errorController.get404);
mongoose
.connect(MONGODB_URI)
.then(result => {
app.listen(3000);
console.log('CONNECTED')
})
.catch(err => {
console.log(err);
});
最后但并非最不重要的一點是反應組件,魔術發生的地方:
class App extends Component {
constructor(props) {
super(props);
this.state = {
students: null,
edit: 'none',
add: 'block',
studentId: null,
firstName: '',
lastName: ''
};
}
handleFirstNameChange = (e) => {
this.setState({firstName: e.target.value});
console.log(this.state.firstName)
}
handleLastNameChange = (e) => {
this.setState({lastName: e.target.value});
}
editStudent = id => {
const requestOptions = {
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({firstName: this.state.firstName , lastName: this.state.lastName}),
};
console.log(id)
fetch("/class/update/" id, requestOptions)
.then((response) => {
console.log('this is response')
return response.json();
})
.catch((err) => {
console.log(err)
})
}
render() {
if (!this.state.students) return null;
const studentNames = this.state.students.map(student => <Draggable bounds="parent" key={student.id}><div className="handle"><img onClick={() => this.getStudent(student.id)} className="imgLogo" src={user} alt="React - Node 應用程式中的 POST 和 PATCH 表單操作后瀏覽器 URL 發生更改"/><div></div> {student.firstName}<div></div> {student.lastName}<div></div> <div><div></div><img onClick={() => this.showForm(student.id)} className="imgBox" src={edit} alt="React - Node 應用程式中的 POST 和 PATCH 表單操作后瀏覽器 URL 發生更改"/><img onClick={() => this.deleteStudent(student.id)} className="imgBox" src={trash} alt="React - Node 應用程式中的 POST 和 PATCH 表單操作后瀏覽器 URL 發生更改"/></div></div></Draggable>);
return (
<div className="float-container">
<divclassName="container float-child">{studentNames}
</div>
<div className="float-child">
<div><h4>Teacher:</h4><div></div><p>FIRSTNAME LASTNAME</p></div>
<h3>Student Info</h3>
<div id = "editForma">
<form>
<label >First Name:</label>
<input type="text" name="firstName" value={this.state.firstName} onChange={this.handleFirstNameChange} />
<div></div>
<br></br>
<label >Last Name:</label>
<input type="text" name="lastName" value={this.state.lastName} onChange={this.handleLastNameChange}/>
<button className="button button2" type="submit" onClick={() => this.editStudent(this.state.studentId)}>Edit Student</button>
</form>
</div>
</div>
</div>
);
}
}
export default App;
現在,當我選擇要編輯的學生時,我將名字和姓氏編輯為“Kate”和“smith”,在請求程序結束時,我的頁面轉到http://localhost:8080/?firstName=Kate&lastName=Smith,這是我不明白的部分。
現在,一旦它導航到那里,即使我重繪 頁面并回傳http://localhost:8080/,它也會“卡住”。
至于錯誤,我在 95% 的情況下都沒有收到任何錯誤,就在我收到錯誤時:
this is body { firstName: 'Kate', lastName: 'Smith' }
[1] MongoServerError: not primary
[1] at MessageStream.messageHandler (/Users/milospopovic/Desktop/Code/teacher-solo/node_modules/mongodb/lib/cmap/connection.js:462:30)
[1] at MessageStream.emit (node:events:390:28)
[1] at processIncomingData (/Users/milospopovic/Desktop/Code/teacher-solo/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
[1] at MessageStream._write (/Users/milospopovic/Desktop/Code/teacher-solo/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
[1] at writeOrBuffer (node:internal/streams/writable:390:12)
[1] at _write (node:internal/streams/writable:331:10)
[1] at MessageStream.Writable.write (node:internal/streams/writable:335:10)
[1] at TLSSocket.ondata (node:internal/streams/readable:777:22)
[1] at TLSSocket.emit (node:events:390:28)
[1] at addChunk (node:internal/streams/readable:324:12) {
[1] topologyVersion: { processId: new ObjectId("6226493d3f6cbc2e7ec62cd9"), counter: 54 },
[1] ok: 0,
[1] code: 10107,
[1] codeName: 'NotWritablePrimary',
[1] '$clusterTime': {
[1] clusterTime: new Timestamp({ t: 1647717344, i: 2 }),
[1] signature: {
[1] hash: new Binary(Buffer.from("c1c7efa296c48125954f75a0da484b63fd9a69de", "hex"), 0),
[1] keyId: new Long("7030875868872310785")
[1] }
[1] },
[1] operationTime: new Timestamp({ t: 1647717343, i: 1 }),
[1] [Symbol(errorLabels)]: Set(1) { 'RetryableWriteError' }
[1] }
uj5u.com熱心網友回復:
您必須使用 fom 的 onSubmit 屬性來傳遞您的請求處理程式函式。請記住接收事件引數并運行“event.preventDefault()”,以防止默認重定向和重定向行為。
<form onSubmit={
onClick={(event) => {
event?.preventDefault()
this.editStudent(this.state.studentId)
}
}}>
<label >First Name:</label>
<input
type="text" name="firstName"
value={this.state.firstName}
onChange={this.handleFirstNameChange} />
<div></div>
<br></br>
<label >Last Name:</label>
<input
type="text"
name="lastName" value={this.state.lastName}
onChange={this.handleLastNameChange}/>
<button className="button button2" type="submit" >Edit Student</button>
</form>
如果您只將按鈕的“型別”屬性更改為“按鈕”而不是“提交”,它也許也可以。我從來沒有這樣做過,但也許它有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446749.html
