我有一个用vite初始化的react js应用程序,我想添加一个Node.js后端,但是我不能,当我添加index.js并运行命令时,它只初始化react,不识别帖子和快递路线。有人能帮帮我吗?这是我的App.jsx和index.js:
应用程序。JSX(它是由main初始化的。Jsx,但它只是vite代码):
import { ResolutionList } from "./components/resolutions/ResolutionList";
import { ResolutionForm } from "./components/resolutions/ResolutionForm";
import {BrowserRouter as Router,Route, Routes as Switch} from "react-router-dom";
import { SearchBar } from "./components/search/SearchBar";
import {Login} from "./components/screens/Login";
function ShowResolutions() {
return (
<>
<ResolutionForm />
<ResolutionList />
</>
);
}
function App() {
return (
<>
<Router>
<Switch>
<Route path="/" element={<ShowResolutions />} />
<Route path="/search" element={<SearchBar />} />
<Route path="/login" element={<Login />} />
</Switch>
</Router>
</>
);
}
export default App;
这些路由指向的react组件在我没有添加NodeJs服务器时工作得很好。index.js:
const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const { handleLogin } = require('./controllers/user.controller');
const bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.set('port',process.env.PORT || 3000);
app.set('app',path.join(__dirname, 'app'));
app.post('/api/login', handleLogin);
module.exports = app;
user.controller.js与路由登录:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const handleLogin = (req, res) => {
const { username, password } = req.body;
console.log("username: ", username, "password: ", password);
};
module.exports = {
handleLogin
}
更新:在做了hyptf告诉我的事情之后,我的应用程序在正确的路线上启动,但当我想登录一个用户时,它给我:tp://127.0.0.1:5173/api/login 500 (Internal Server Error)
这是react的login组件:
import { useState } from 'react';
export function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
})
.then((response) => {
if (response.ok) {
window.location.href = '/';
} else {
alert('Error al iniciar sesión. Por favor, intente nuevamente.');
}
})
.catch((error) => {
console.error(error);
});
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Usuario:</label>
<input
type="text"
id="username"
value={username}
onChange={(event) => setUsername(event.target.value)}
/>
</div>
<div>
<label htmlFor="password">Contraseña:</label>
<input
type="password"
id="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
/>
</div>
<button type="submit">Iniciar sesión</button>
</form>
);
}
后端用户post在index.js和handleLogin上面提交。我尝试了许多解决方案和教程(包括ChatGPT),但仍然不起作用。
如果你使用vite,那么你有一个vite.config.js
你需要在那里设置一个代理。
你的简历是这样的:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
在plugins
后面加上:
server: {
proxy: {
'/api': 'http://localhost:YOURPORT', //replace YOURPORT
}
},
资源:https://vitejs.dev/config/server-options.html
如果您正在使用CRA:https://create-react-app.dev/docs/proxying-api-requests-in-development/