React Hooks:如何向服务器发出 POST 请求

IT技术 node.js reactjs express
2021-05-11 01:25:33

我是初学者。我试图以简单的形式实现来自 React.js 的 POST 请求,但我不知道如何将 POST 请求发送到数据库。我想我也需要<form action="URL">任何帮助将不胜感激。下面是 React.js(frontend) 的代码

import GameTestResult from './GameTestResult';

export default function App() {
 const[data, setData] = useState([]);
 const [formData, setFormData] = useState("");

 useEffect (() => {
  fetch('http://localhost:3000/game')
  .then(res => res.json()) 
 .then(result => setData(result.rows))
  .catch(err => console.log("error"))
  },[]);

  const handleChange = event => {
    setFormData(event.target.value)
    }
    
    const eventHandler = event => {
      event.preventDefault();
      setFormData("");
    }

  return (
    <div className="App">
        <form  method="post" onSubmit = {eventHandler}>
          <input value = {formData} onChange = {handleChange} />
          <button type="submit">click</button>
        </form>
      
      {data && data.map((element, index)=>(
            <GameTestResult
              name = {element.name}
              key={element.index}
            />
      ))} 

      </div>
  );
}

这是来自 express.js(backend) 的代码

var router = express.Router();
const pool = require("../config.js");
var cors = require('cors');



router.get("/game", cors(), (req, res) => {
  pool
    .query("SELECT * FROM game")
    .then((data) => res.json(data))
    .catch((e) => {
      res.sendStatus(404), console.log(e);
    });
});



router.post("/game", (req, res) => {
  const { name } = req.body; 
 
  pool
    .query('INSERT INTO game(name) values($1);', [name])
    .then(data => res.status(201).json(data))
    .catch(e => res.sendStatus(404));
 });
 

module.exports = router;
2个回答

您可以执行以下操作:

安装组件时获取游戏。并在提交表单时提交新游戏。

export default function App() {
  const [data, setData] = useState([])
  const [formData, setFormData] = useState('')

  useEffect(() => {
    fetchGames() // Fetch games when component is mounted
  }, [])

  const fetchGames = () => {
    fetch('http://localhost:3000/game', {
      method: 'GET',
    })
      .then((res) => res.json())
      .then((result) => setData(result.rows))
      .catch((err) => console.log('error'))
  }

  const saveGames = () => {
    fetch('http://localhost:3000/game', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: formData, // Use your own property name / key
      }),
    })
      .then((res) => res.json())
      .then((result) => setData(result.rows))
      .catch((err) => console.log('error'))
  }

  const handleSubmit = (event) => {
    event.preventDefault()
    saveGames() // Save games when form is submitted
  }

  const handleChange = (event) => {
    setFormData(event.target.value)
  }

  return (
    <div className="App">
      {/* method="post" not needed here because `fetch` is doing the POST not the `form` */}
      {/* Also, note I changed the function name, handleSubmit */}
      <form onSubmit={handleSubmit}>
        <input type="text" name="name" value={formData} onChange={handleChange} />
        <button type="submit">click</button>
      </form>

      {data &&
        data.map((element, index) => (
          <GameTestResult name={element.name} key={element.index} />
        ))}
    </div>
  )
}

您可以阅读有关如何使用获取和这个有关表单中RecatJS是如何工作的。

  • 添加名称作为"name"输入
  • 监听 onChange 并设置数据setFormData({[event.target.key]: event.target.value}),例如数据将是{name: "Tony"}
  • 在按钮的 onClick 操作上调用 POST 请求,如下面的代码
  • JSON.stringify(data) 将 js 对象发送到服务器时将其转换为 JSON 很重要
import GameTestResult from './GameTestResult'

export default function App() {
  const [data, setData] = useState([])
  const [formData, setFormData] = useState({})

  useEffect(() => {
    fetch('http://localhost:3000/game')
      .then((res) => res.json())
      .then((result) => setData(result.rows))
      .catch((err) => console.log('error'))
  }, [])

  const handleChange = (event) => {
    setFormData({ [event.target.name]: event.target.value })
  }

  const eventHandler = (event) => {
    fetch('http://localhost:3000/game', {
      method: 'POST',
      body: JSON.stringify(formData),
    })
      .then((res) => res.json())
      .then((result) => {
        console.log(result)
        setFormData('')
      })
      .catch((err) => console.log('error'))
  }

  return (
    <div className="App">
      <form>
        <input name="name" value={formData.name || ''} onChange={handleChange} />
        <button onClick={eventHandler}>click</button>
      </form>

      {data &&
        data.map((element, index) => (
          <GameTestResult name={element.name} key={element.index} />
        ))}
    </div>
  )
}