だら$ちっぷす

仕事の覚書です

Node.js POSTを使ってPostgreSQL にinsertする

★2019-12-19 これもasyncで書き直しました!
  (関数をasyncって宣言すると、その関数内ではawaitってキャストした関数が    同期になるよ!ただしpromise返すやつだけ)
【サーバ側】

app.post('/sql/ins_work', 
async (req, res) => 
{
    const sql = 'insert into work(' +
                    'userid,' +
                    'qno,' +
                    'anstime' +
                ')' +
                ' values(' +
                    '$1,' +
                    '$2,' +
                    'to_timestamp($3 / 1000.0)' +
                ')';

    const values = [
        req.body.userid,        //1
        req.body.qno,           //2
        req.body.anstime        //3 time
    ];

    try
    {
        const resq = await client.query(sql, values);

        res.send('OK');        //ACKを返す
                        //(これを送らないと処理が終了したことが送られないので
                        // クライアント側はずっと待ったままになってしまう。
                        // 返事は大事)
    }
    catch(err) 
    {
        res.send(err.stack);    //ACKを返す
    }
});


【ブラウザ側】

async function ins_work()
{
    //json形式でデータセット
    var data =
    {
        userid:   'banjo',
        qno:    1,
        anstime:   (new Date()).getTime()
    };

    try
    {
        const res = await fetch('./sql/ins_work', 
        {
            method:     'POST',
            body:       JSON.stringify(data),   //json文字列に変換してセット
            headers:
            {
                'Content-Type': 'application/json'    //データがjson形式であることを明記
            }
        }
        const text = await res.text();

        if(text == "OK")
            console.log("[OK]ins_work");
        else
            console.error("[DB ERROR]", text);
    )
    catch(err)
    { 
        console.error("[fetch ERROR]ins_work", error);
    }
}