1
4

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 5 years have passed since last update.

curlコマンドでJSONデータをPOSTリクエストしてみた

1
Posted at

コマンドの例文

curl -H "Content-Type: application/json" -X POST -d "{ \"key\" : \"value\"}" url

ポイント①
-H "Content-Type: application/json"
を付ける

ポイント②
-X POST
を付ける

ポイント③
-d "{ \"key\" : \"value\"}"
JSON(連想配列)のkeyとvalueは\"で囲む
↓ダメな例①
-d `{ "name" : "nodejsTaro" }`
↓ダメな例②
-d "{ name : nodejsTaro }"

テストしてみる

サーバーはこんな感じのnode.jsサーバーだったと仮定する。

server.js
"use strict";

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

// middleware
app.use(express.json());
app.use(express.urlencoded());

// 好きな設定にする
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.header(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
  );
  next();
});

// /helloWorldへのPOSTリクエストに対する処理
app.post("/helloWorld", function (req, res) {
  const name = req.body.name;
  console.log(`hello ${name}`);
  res.status(200).send(`Nice to meet you, ${name}`);
});

// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}...`);
});

module.exports = app;

実行

C:\Users\user1\mydir> curl -H "Content-Type: application/json" -X POST -d "{ \"name\" : \"nodejsTaro\" }" http://localhost:8080/helloWorld
Nice to meet you, nodejsTaro
1
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?