0
0

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.

【メモ】Node.jsでAPI通信するサンプル実装

Posted at

下記の動画のメモです。

ゼロから半年でWeb系エンジニアになろう【完全まとめ版】
https://www.youtube.com/watch?v=O9D18lhLa2Y

# expressをインストール
npm i express
app.js
const express = require('express')
const app = express()
const port = 3000 //通信の宛先を区別する どのアプリケーションと通信したいのか識別するもの
let booklog = {} //初期化する

app.use(express.json())

// 投稿POSTする
app.post('/booklog', (req, res) => {
  booklog = req.body

  if (!(booklog.name && booklog.text)) {
    res.json({
      "ok": false,
      "error": "invalid parameter"
    })
  }

  res.json({
    "ok": true,
    "booklog": booklog
  })
})

// 取得する
app.get("/booklog", (req, res) => {
  res.json({
    "ok": true,
    "booklog": [
      booklog
    ]
  })
})

// ポート3000番でサーバーを立ち上げる
app.listen(port, () => {
  console.log(`App listening at http://localhosst:${port}`)
})

# サーバーを起動する
node app.js

API通信するための叩くコマンド

# POST
curl -X POST -H "Content-Type: application/json" -d '{"name":"キングダム", "text":"熱い"}' localhost:3000/booklog

# GET
curl -X GET -H "Content-Type: application/json" localhost:3000/booklog
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?