1. ホーム
  2. javascript

[解決済み] Node.jsでJSONオブジェクトで応答する(オブジェクト/配列をJSON文字列に変換する)

2022-10-26 06:22:24

質問

私はバックエンドコードの初心者で、私にJSON文字列を応答する関数を作成しようとしています。私は現在、例からこれを持っています。

function random(response) {
  console.log("Request handler 'random was called.");
  response.writeHead(200, {"Content-Type": "text/html"});

  response.write("random numbers that should come in the form of json");
  response.end();
}

これは基本的に、文字列 "JSON形式で来るはずの乱数" を出力するだけです。私がやりたいことは、任意の数のJSON文字列で応答することです。この関数は、クライアント側でその値を別のものに渡す必要がありますか?

あなたの助けに感謝します!

どのように解決するのですか?

使用方法 res.json を Express で使用します。

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

あるいは

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}