我怎么将输入的数值提交到数据库?

huangapple go评论65阅读模式
英文:

How i can post from input values to Database?

问题

以下是您要翻译的内容:

我想从此处的输入发送POST请求到数据库我是新手正在尝试完成这个任务有人能帮我吗请问我需要做什么来实现我的目标

import { useState, useEffect } from "react";
import axios from "axios";
import Task from "./Task";
import "./App.scss";

function App() {
  // 输入值
  const [val, setVal] = useState("");
  const [todos, setTodos] = useState([]);
  const [message, setMessage] = useState([]);

  const addTodos = async (e) => {
    if (val === "") return;
    e.preventDefault();

    const res = await axios
      .post("http://localhost:8000/message")
      .then((response) => console.log(response))
      .catch((error) => console.log(error));

    setTodos([...todos, val]);
    setVal("");
  };

  useEffect(() => {
    const fetchProducts = async () => {
      const res = await axios.get("http://localhost:8000/message");
      setMessage(res.data);
    };
    fetchProducts();
  }, []);

  const handleDelete = (id) => {
    setTodos(todos.filter((_, key) => key !== id));
  };

  return (
    <div className="App">
      {/* 更改值*/}
      <form onSubmit={addTodos}>
        <input
          onChange={(e) => setVal(e.target.value)}
          value={val}
          type="text"
        />
        <button type="submit">Add</button>
      </form>
      <ul>
        {todos.map((todo, key) => (
          <Task todo={todo} key={key} myKey={key} handleDelete={handleDelete} />
        ))}
      </ul>
      {message.map((e) => (
        <div>{e.todo}</div>
      ))}
    </div>
  );
}

export default App;

// 服务器JS

const express = require("express");
const cors = require("cors");

const { Client } = require("pg");
const client = new Client({
  user: "jj",
  host: "localhost",
  database: "dbname",
  password: "rootuser",
  port: 5432,
});
client.connect();
const app = express();
app.use(cors());
app.use(express.json());

app.get("/message", async (req, res) => {
  const { rows } = await client.query(`SELECT * from todo`);
  res.send(rows);
});

app.listen(8000, () => {
  console.log(`服务器正在5174端口上运行。`);
});

对于您的最后一个问题,是的,您应该在Node.js服务器中创建一个处理POST请求的端点,然后在React中使用useEffect来发送POST请求以将数据发送到该端点。这将允许您在React应用中将数据存储到数据库中。

英文:

I want to send post request from the input here to the database, im beginner and trying to manage to do that, can someone help me here please what i have to do in order to achieve my goal ?

import { useState, useEffect } from &quot;react&quot;;
import axios from &quot;axios&quot;;
import Task from &quot;./Task&quot;;
import &quot;./App.scss&quot;;
function App() {
//Value of Input
const [val, setVal] = useState(&quot;&quot;);
const [todos, setTodos] = useState([]);
const [message, setMessage] = useState([]);
const addTodos = async (e) =&gt; {
if (val == &quot;&quot;) return;
e.preventDefault();
const res = await axios
.post(&quot;http://localhost:8000/message&quot;)
.then((response) =&gt; console.log(response))
.catch((error) =&gt; console.log(error));
/** */
setTodos([...todos, val]);
setVal(&quot;&quot;);
/** */
};
useEffect(() =&gt; {
const fetchProducts = async () =&gt; {
const res = await axios.get(&quot;http://localhost:8000/message&quot;);
setMessage(res.data);
};
fetchProducts();
}, []);
const handleDelete = (id) =&gt; {
setTodos(todos.filter((_, key) =&gt; key !== id));
}; //#endregion
return (
&lt;div className=&quot;App&quot;&gt;
{/** On change values*/}
&lt;form onSubmit={addTodos}&gt;
&lt;input
onChange={(e) =&gt; setVal(e.target.value)}
value={val}
type=&quot;text&quot;
/&gt;
&lt;button type=&quot;submit&quot;&gt;Add&lt;/button&gt;
&lt;/form&gt;
&lt;ul&gt;
{todos.map((todo, key) =&gt; (
&lt;Task todo={todo} key={key} myKey={key} handleDelete={handleDelete} /&gt;
))}
&lt;/ul&gt;
{message.map((e) =&gt; (
&lt;div&gt;{e.todo}&lt;/div&gt;
))}
&lt;/div&gt;
);
}
export default App;

//server js

const express = require(&quot;express&quot;);
const cors = require(&quot;cors&quot;);
const { Client } = require(&quot;pg&quot;);
const client = new Client({
user: &quot;jj&quot;,
host: &quot;localhost&quot;,
database: &quot;dbname&quot;,
password: &quot;rootuser&quot;,
port: 5432,
});
client.connect();
const app = express();
app.use(cors());
app.use(express.json());
app.get(&quot;/message&quot;, async (req, res) =&gt; {
const { rows } = await client.query(`SELECT * from todo`);
res.send(rows);
});
app.listen(8000, () =&gt; {
console.log(`Server is running on port 5174.`);
});

Should i also create a path in node js for the same server for the post request, then do the same in react using useEffect ?

答案1

得分: 1

你需要在你的 server.js 文件中添加一个新路由,像这样:

app.get("/message", async (req, res) => {
   const { rows } = await client.query("SELECT * from todo");
   res.send(rows);
});

app.post("/message", async (req, res) => {
   // 在数据库中运行一些逻辑
});

这将使前端在调用 /messageGET 请求时,运行 app.get("/message") 代码,但当你调用 /messagePOST 请求时,它将运行 app.post 代码。

希望这有所帮助。

P.S. 你可能需要运行一些中间件来解析 POST 请求中的数据。基本上,POST 请求的想法是,客户端将发送一些数据,比如 JSON,到请求的主体,然后你将使用中间件来解析请求的主体成可编辑的 JavaScript 对象,然后用于与数据库执行某些操作。

英文:

You would want to add a new route in your server.js file like this:

app.get(&quot;/message&quot;, async (req, res) =&gt; {
const { rows } = await client.query(`SELECT * from todo`);
res.send(rows);
});
app.post(&quot;/message&quot;, async (req, res) =&gt; {
// run some logic in the database
});

This will make it so in the frontend, when you call a GET request to /message, then it will run the app.get(&quot;/message&quot;) code, but when you call a POST request to /message, it will will run the app.post code.

Hope this helps.

P.S. You may need to run some middleware to parse the data on the POST request. Essentially what is the idea with POST requests is that the client will send some data, like JSON, to the body of the request, and then you will use middleware to parse the request's body into editable JS objects that will be used to do something with the database.

huangapple
  • 本文由 发表于 2023年4月1日 00:09:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900640.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定