每個人!我正在嘗試使用 Node/React/Mongoose 構建一個沒有 CRA 命令的應用程式,該命令還包括自定義 webpack。
我設法在一個 React 頁面 (App.jsx) 中構建了所有內容,但代碼看起來很亂。我設法通過首先從資料庫中獲取資料來構建它,然后圍繞它構建所有東西。現在可行,但我想更進一步。無論獲取的資料如何,我都想構建一個應用程式。
現在,我發現自己遇到的問題可能會更好地顯示在幻燈片中。我該如何解決這個問題?我試過改變路徑,但沒有運氣。
一旦我進入主頁,就會呈現導航欄。我也可以重繪 ,而且不會壞。

當我使用導航欄導航到 /teacher 時,它會很好地加載所有內容。

但是當我手動重繪 或鍵入 url localhost8080/teacher 時問題就開始了。它獲取原始資料而不是組件。

這是我與該問題相關的代碼:
服務器.js
app.use('/teacher', authRoutes);
app.use('/class', classRoutes);
app.get('/', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
路由.js
router.get('/signup', authController.teacherList);
控制器
exports.teacherList = (req, res, next) => {
Teacher.find()
.then(teacher => {
return res.send(teacher)
})
.catch(err => console.log(err));
}
應用程式.jsx
import React, { Component } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import TeacherComponent from './Teacher'
import ClassComponent from './Class'
export default class App extends Component {
render() {
return (
<Router>
<div>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<ul className="navbar-nav mr-auto">
<li><Link to={'/class'} className="nav-link">Class</Link></li>
<li><Link to={'/teacher'} className="nav-link">Teacher</Link></li>
</ul>
</nav>
<hr />
<Routes>
<Route path='/class' element={<ClassComponent />} />
<Route path='/teacher' element={<TeacherComponent />} />
</Routes>
</div>
</Router>
);
}
}
老師.jsx
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom'
import Select from 'react-select';
import 'bootstrap/dist/css/bootstrap.min.css';
class Teacher extends Component {
constructor(props) {
super(props);
this.state = {
teachers: [],
isSignedUp: false,
firstName : '',
lastName: '',
email: '',
password: '',
studentsClass: {
students: []
}
};
}
componentDidMount() {
fetch('http://localhost:8080/teacher')
.then(response => response.json())
.then(teachers => this.setState({teachers: teachers}));
}
handleFirstName = (e) => {
this.setState({firstName: e.target.value});
}
handleLastName = (e) => {
this.setState({lastName: e.target.value});
}
handleEmail = (e) => {
this.setState({email: e.target.value});
}
handlePassword = (e) => {
this.setState({password: e.target.value});
}
signUp = () => {
const requestOptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({firstName: this.state.firstName , lastName: this.state.lastName, email: this.state.email , password: this.state.password}),
};
fetch("/teacher/signup", requestOptions)
.then((response) => {
return response.json();
})
.then(() => {
fetch('http://localhost:8080/class')
.then(response => response.json())
.then(teachers => this.setState({teachers: teachers}));
})
.catch((err) => {
console.log(err)
})
}
render() {
// const teachers = this.state.teachers.map(teacher => <div key={teacher._id}>{teacher.firstName} - {teacher.lastName}</div>);
const teachers = []
for (let i = 0; i < this.state.teachers.length; i ) {
teachers.push({label: this.state.teachers[i].firstName ' ' this.state.teachers[i].lastName})
}
return (
<div>
<div className="container">
<div className="row" style={{marginTop: "100px"}}>
<div className="col-md-4"></div>
<div className="col-md-4">
<Select placeholder="Select teacher"options={ teachers } />
</div>
<div className="col-md-4"></div>
</div>
</div>
<div></div>
<div style={{display: "flex", alignItems: "center", justifyContent: "center", marginTop: "100px"}}><h5>Signup:</h5></div>
<div style={{margin: "20px auto", borderTop: "2px solid black", width: "400px", textAlign: "center"}}>
<form style={{marginTop: "30px"}} onSubmit={(event) => {
event.preventDefault()
this.signUp(this.state.teacher)
}} >
<input style={{textAlign: "center"}} type="text" name="firstName" placeholder="First Name" value={this.state.firstName} onChange={this.handleFirstName} />
<div></div>
<br></br>
<input style={{textAlign: "center"}} type="text" name="lastName" placeholder="Last Name" value={this.state.lastName} onChange={this.handleLastName}/>
<div></div>
<br></br>
<input style={{textAlign: "center"}} type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmail}/>
<div></div>
<br></br>
<input style={{textAlign: "center"}} type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePassword}/>
<div></div>
<br></br>
<input className="button button2" type="submit" />
</form>
</div>
</div>
);
}
}
export default Teacher;
還有代理請求的 webpack:
const webpack = require("webpack");
const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "./src/index.js"),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: ["file-loader"]
}
],
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
mode: process.env.NODE_ENV,
output: {
path: path.resolve(__dirname, "./docs"),
filename: "bundle.js",
},
// [webpack-dev-server] "hot: true" automatically applies HMR plugin, you don't have to add it manually to your webpack configuration.
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
// contentBase is deprecated by static in webpack v5
proxy: {
'/': 'http://localhost:3000/',
},
// contentBase: path.resolve(__dirname, "./docs"),
hot: true,
},
};
uj5u.com熱心網友回復:
問題是您如何配置 server.js 檔案
app.use('/teacher', authRoutes);
app.use('/class', classRoutes);
app.get('/', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
現在假設您正在向您的服務器發送請求以獲取 url 中的資料,/teacher現在它的作業非常好。因為,它會遇到第一行并向您發送原始 json 并完成它。
一種解決方案是將所有 api 模塊保存在“/api”附加路徑中。因此,它們不會與您的常規路由沖突。
app.use('/api/teacher', authRoutes);
app.use('/api/class', classRoutes);
app.get('/', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
這應該可以解決您的問題。
編輯:最后一條路線應始終回傳主頁。所以,在路徑匹配中需要一顆星
app.get('/*', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
uj5u.com熱心網友回復:
您的服務器在 localhost 8080 上運行,因此客戶端可能在 localhost 上運行其他類似 3030 的東西,請檢查一下,因為我看到您在 8080 上呼叫服務器 api。
你可以優化你的代碼 -
<Route path='/class' element={()=><ClassComponent teacher={this.state.teachers} />} />
<Route path='/teacher' element={()=><TeacherComponent teacher={this.state.teachers/>} />
試試這個&請同時上傳 ClassComponent 和 TeacherComponent。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/446438.html
標籤:javascript 节点.js 反应 表示 网页包
上一篇:在Vue3中,使用PrimeVue,有沒有辦法在單擊時將漢堡選單按鈕更改為X?
下一篇:在函式內更改向量中的一個元素
