9

node.js への次の要求で資格情報 JSON オブジェクトを送信しています。

credentials = new Object();
credentials.username = username;
credentials.password = password;

$.ajax({
    type: 'POST',
    url: 'door.validate',
    data: credentials,
    dataType: 'json',
    complete: function(validationResponse) {
        ...
    }
});

サーバー側では、送信された資格情報を JSON オブジェクトにロードして、さらに使用したいと考えています。

ただし、req オブジェクトから JSON を取得する方法がわかりません...

http.createServer(
    function (req, res) {
         // How do i acess the JSON
         // credentials object here?
    }
).listen(80);

(関数(req、res)にディスパッチャーがあり、さらにreqをコントローラーに渡すため、.on( 'data'、...)関数を使用したくありません)

4

2 に答える 2

16

サーバー側では、jQuery データを JSON ではなくリクエスト パラメータとして受け取ります。データを JSON 形式で送信すると、JSON を受信し、解析する必要があります。何かのようなもの:

$.ajax({
    type: 'GET',
    url: 'door.validate',
    data: {
        jsonData: "{ \"foo\": \"bar\", \"foo2\": 3 }"
        // or jsonData: JSON.stringify(credentials)   (newest browsers only)
    },
    dataType: 'json',
    complete: function(validationResponse) {
        ...
    }
});

サーバー側では、次のことを行います。

var url = require( "url" );
var queryString = require( "querystring" );

http.createServer(
    function (req, res) {

        // parses the request url
        var theUrl = url.parse( req.url );

        // gets the query part of the URL and parses it creating an object
        var queryObj = queryString.parse( theUrl.query );

        // queryObj will contain the data of the query as an object
        // and jsonData will be a property of it
        // so, using JSON.parse will parse the jsonData to create an object
        var obj = JSON.parse( queryObj.jsonData );

        // as the object is created, the live below will print "bar"
        console.log( obj.foo );

    }
).listen(80);

これは GET で機能することに注意してください。POST データを取得するには、こちらをご覧ください: Node.js で POST データを抽出するにはどうすればよいですか?

オブジェクトを JSON にシリアル化し、jsonData に値を設定するには、JSON.stringify(credentials)(最新のブラウザーで) またはJSON-jsを使用できます。例: jQuery での JSON へのシリアル化

于 2012-08-16T21:03:55.803 に答える
-5

Console.log 要求

http.createServer(
    function (req, res) {

    console.log(req); // will output the contents of the req

    }
).listen(80);

正常に送信された場合、投稿データはどこかに存在します。

于 2012-08-16T20:24:27.037 に答える