我正在开发 React 应用程序有一段时间了。该应用程序最初是使用 Create-React-App 命令创建的。
当我需要实现一个表单时,我进入了这个阶段,如果用户无法通过自动完成输入找到它,他可以手动添加一个人。所有人员都存储在位于 src/components/lists 中的 persons.js 文件中,看起来像这样
const persons = [
{ name: "Person 1", id: "1" },
{ name: "Person 2", id: "2" },
{ name: "Person 3", id: "3" },
...];
// Export
export { persons };
当用户通过它应该永久(对其他用户可见)的表单添加新人时,意味着,我需要更改文件 persons.js 并且不想使用 localstorage ...
以我有限的知识,我得出的结论是我需要使用我安装的 Express.js(以及 Axios)并尝试实现 form
Addperson.js 位于 src/components/other 中,如下所示:
import React, { useState } from 'react';
import axios from 'axios';
function Addperson() {
const [name, setName] = useState('');
const [id, setId] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await axios.post('/api/persons', { name, id });
console.log(res.data);
} catch (err) {
console.error(err);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Ime:
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
</label>
<br />
<label>
ID:
<input type="text" value={id} onChange={(e) => setId(e.target.value)} />
</label>
<br />
<button type="submit">Add Person</button>
</form>
);
}
export default Addperson;
Server.js 在应用根目录下:
const express = require('express');
const bodyParser = require('body-parser');
const { persons } = require('./src/components/lists/persons');
const app = express();
const port = 5000;
app.use(bodyParser.json());
app.post('/api/persons', (req, res) => {
const { name, id } = req.body;
persons.push({ name, id });
res.json(persons);
});
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
package.json:
{
"name": "firstapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.2.0",
"@fortawesome/free-brands-svg-icons": "^6.1.1",
"@fortawesome/free-regular-svg-icons": "^6.2.0",
"@fortawesome/free-solid-svg-icons": "^6.2.0",
"@fortawesome/react-fontawesome": "^0.2.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.3.3",
"babel-plugin-macros": "^3.1.0",
"bootstrap": "^5.1.3",
"bootstrap-icons": "^1.10.3",
"date-fns": "^2.29.3",
"express": "^4.18.2",
"file-saver": "^2.0.5",
"firebase": "^9.15.0",
"fs": "^0.0.1-security",
"html-docx-js": "^0.3.1",
"html-react-parser": "^3.0.7",
"react": "^18.1.0",
"react-bootstrap": "^2.3.1",
"react-bootstrap-icons": "^1.10.2",
"react-datepicker": "^4.8.0",
"react-dom": "^18.1.0",
"react-router-dom": "^6.4.5",
"react-scripts": "5.0.1",
"react-select": "^5.4.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
React 应用程序(客户端)运行良好,但看起来我无法正常工作 express server.js.
当我尝试运行 node server.js 时,我得到:
C:\Users\xxxx\Desktop\web\firstapp\src\components\lists\persons.js:62
export { persons };
^^^^^^
SyntaxError: Unexpected token 'export'
当我尝试提交用户时,我得到:xhr.js:247 POST http://localhost:3000/api/persons 404 (Not Found)
有人可能在设置中看到任何明显的错误吗?欢迎任何帮助。谢谢
你不能像这样从
Express
导入 React 组件,然后尝试修改变量并让应用程序上的其他用户看到该更改。你已经毕业了,至少需要一个database
.
我强烈建议跳入
Firebase
以利用 Firestore
,因为您可以存储 Persons
对象数组,然后简单地创建一个 Firestore“侦听器”,当对内部的 Persons 对象进行更改时,每个 React 用户的 UI 都会看到该侦听器Firestore。
否则你正在考虑设置类似 MySQL + Websockets 的东西。
此外,如果您必须直接编辑客户端之间共享的本地后端文件,您可以使用
fs
.
读取数据:
const fs = require('fs');
let json = fs.readFileSync('random.json');
let data = JSON.parse(json);
console.log(data);
写文件:
const fs = require('fs');
const data = {
foo: 'bar'
};
const jsonString = JSON.stringify(data
fs.writeFileSync('random.json', jsonString);