使用React和Express组合实现post请求

构成

image.png

使用React的App.tsx与node+express一起构建,向后端发送post请求的概念。
后端与MySQL数据库连接。

代码 (daima)

  const App = async () => {
    try {
      await axios.post("http://localhost:3100/api", {
        date: "2023/02/07",
        id: 1,
        name: "name",
      });
    } catch (error) {
      console.error("error=" + error);
    }
  };
const express = require("express");
const cors = require("cors");
const app = express();
const mysql = require("mysql2");
require("dotenv").config();

const connection = mysql.createConnection({
  host: process.env.ENDPOINT,
  user: process.env.NAME,
  password: process.env.PASSWORD,
  database: process.env.DBNAME,
});

app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.post("/api", (req: any, res: any) => {
  const { date, seat_id, integrated_id } = req.body;
  console.log(date);//2023/02/07
  console.log(id);//1
  console.log(name);//name

  const insertQuery = `INSERT INTO ${process.env.DBNAME}.${process.env.DBTABLE} (date, id, name) VALUES ("${date}",${id}, "${name}");`;

  connection.query(insertQuery, (error: any, results: any) => {
    if (error) {
      throw error;
    }
    res.status(201).send(`added`);
  });
});

app.listen(3100, () => {
  console.log("Server port 3100 started!");
});

前端使用npm start命令启动,后端使用tsnode index.ts命令启动。index.ts文件内部执行以下操作:

app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

如果不添加此项,它将无法正常工作。

广告
将在 10 秒后关闭
bannerAds