1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】React+Expressの構成でpostを実行する

Posted at

構成

image.png

ReactのApp.tsxからnode+expressで作っている、バックエンドにpostをするイメージです。
バックエンドはMySQLと繋がっています。

コード

App.tsx
  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);
    }
  };
index.ts
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内では

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

を追加しないとうまく動きませんでした。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?