実現したいこと
データベースからランダムに2択の質問を取得
↓
取得した質問と回答ボタンを表示
↓
回答すると集計結果を表示
以上の機能をExpressを使って実現したいです。
該当するコード
JavaScript
1router.get('/question', async (req, res) => { 2//データベースからランダムに質問を取得 3 const fetchedQuestion = await fetchQuestion(); 4//IDを文字列型に変換 5 const strId = fetchedQuestion._id.toString(); 6//個別の質問のページにリダイレクト 7 res.redirect(`/question/${strId}`); 8}); 9 10router.get('/question/:id', async (req, res) => { 11//クエリパラメータのIDから選択された質問を取得 12 const selectedQuestion = await Question.findById(req.params.id); 13//質問内容を表示するページをレンダリング 14 res.render('question', { question: selectedQuestion }); 15}); 16 17router.post('/question/:id', async (req, res) => { 18 console.log(req.params.id); //ここの中身が:idになってしまっている 19//回答数をインクリメントする処理 20 try { 21 if (req.body.countA) { 22 const selectedQuestion = await Question.findByIdAndUpdate(req.params.id, { $inc: { countA: 1 } }); 23 await req.user.answers.push({ questionId: selectedQuestion._id, answer: 'A' }); 24 await req.user.save(); 25 } 26 27 if (req.body.countB) { 28 const selectedQuestion = await Question.findByIdAndUpdate(req.params.id, { $inc: { countB: 1 } }); 29 await req.user.answers.push({ questionId: selectedQuestion._id, answer: 'B' }); 30 await req.user.save(); 31 } 32 33 } catch (e) { 34 console.log(e); 35 } 36 37
個別の質問を表示させるところまでは実装できているのですが(2番目のルーティングまで)、ポスト処理の際に:idの中身をうまく引き継ぐことができず、http://localhost:3000/question/:idにアクセスしてしまっている状態です。
ご教授いただけると嬉しいです。よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。