コマンドの例文
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