LoginSignup
1
1

More than 1 year has passed since last update.

Node.js+expressでリクエストボディを取得

Last updated at Posted at 2022-12-18

前回の記事でnodeからmysql接続してデータ登録をしたので今回はAPIリクエストボディにセットした値でデータ登録をするようにします

リクエストボディを取得するコード

npmやyarnで body-parser をインストールしてください
req.body でリクエストボディが取得できます

// リクエストボディ取得準備
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

/**
 * ユーザー登録
 */
const registerUser = async(userName) => {
  await createConnection()
  const [result, filelds] = await client.query(
    `INSERT INTO users VALUES (0, '${userName}')`
  )
  await client.end()
  return result
}

/**
 * @Controller
 * ユーザー登録API
 */
app.post('/users', async(req, res) => {
  // リクエストボディ.nameプロパティの値を取得
  const result = await registerUser(req.body.name)
  res.send(result ? "ユーザー登録に成功しました" : "ユーザー登録に失敗しました")
})

app.listen(3000)

APIリクエストはこちら

curl --location --request POST 'http://localhost:3000/users' \
--header 'Content-Type: application/json' \
--data-raw '{"name": "operator"}'
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