reactjs 带有express.js(本地主机)设置的React应用程序

ymdaylpp  于 2023-02-22  发布在  React
关注(0)|答案(1)|浏览(86)

我开发react应用程序有一段时间了。这个应用程序最初是使用Create-React-App命令创建的。
当我需要实现一个表单时,我来到了这个阶段,在这个阶段,如果用户无法通过自动完成输入找到一个人,他可以手动添加一个人。所有的人都存储在persons.js文件中,该文件位于src/components/lists中,看起来像这样:

const persons = [
        { name: "Person 1", id: "1" },
        { name: "Person 2", id: "2" },
        { name: "Person 3", id: "3" },
        ...];
    // Export
    export { persons };

当用户通过表单添加一个新人时,它应该是永久的(对其他用户可见),这意味着,我需要更改文件persons.js,不想使用本地存储。
凭借我有限的知识,我得出了这样的结论:我需要使用我安装的Express.js(沿着Axios)并尝试实现表单
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'

当我尝试提交用户时,我得到:
404(未找到)返回首页
有没有人可能看到任何明显的错误设置?任何帮助是受欢迎的。谢谢

c7rzv4ha

c7rzv4ha1#

您无法像这样从Express导入React组件,然后尝试修改变量并让应用上的其他用户看到该更改。您已经升级到至少需要database
我强烈建议跳到Firebase来利用Firestore,因为您可以存储对象的Persons数组,然后只需创建一个Firestore“侦听器”,当对Firestore中的Persons对象进行更改时,每个React用户的UI都会看到该侦听器。
Get realtime updates with Cloud 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);

相关问题