DBにproductsテーブルを作成しており、その中の値を画面に一覧表示したい
しかしproductsが見つからないとエラーが出て進まない
productsは指定しているはずなのですが、足らない記述などあれば教えていただきたいです
app.js
1const express = require('express'); 2const mysql = require('mysql'); 3const app = express(); 4 5const app = express(); 6 7const connection = mysql.createConnection({ 8 host: 'localhost', 9 user: 'root', 10 password: '', 11 database: 'node-test' 12}); 13 14connection.connect((err) => { 15 if (err) { 16 console.log('error connecting: ' + err.stack); 17 return; 18 } 19 console.log('success'); 20}); 21 22app.get('/', (req, res) => { 23 connection.query( 24 'SELECT * FROM products', 25 (error, results) => { 26 res.render('hello.ejs',{products: results}); 27 } 28 ); 29}); 30 31 32app.listen(3000);
hello.ejs
1<!DOCTYPE html> 2<html> 3 <head> 4 <meta charset="utf-8"> 5 <title>hello</title> 6 </head> 7 <body> 8 <ul> 9 <% products.forEach((product) => { %> 10 <li> 11 <div> 12 <span><%= product.id %></span> 13 <span><%= product.name %></span> 14 <span><%= product.price %></span> 15 </div> 16 </li> 17 <% }) %> 18 </ul> 19 </body> 20</html>
undefined ReferenceError: /Users/nagafuji/Desktop/node-test/views/hello.ejs:9 7| <body> 8| <ul> >> 9| <% products.forEach((product) => { %> 10| <li> 11| <div> 12| <span><%= product.id %></span> products is not defined at eval (/Users/nagafuji/Desktop/node-test/views/hello.ejs:12:8) at hello (/Users/nagafuji/Desktop/node-test/node_modules/ejs/lib/ejs.js:691:17) at tryHandleCache (/Users/nagafuji/Desktop/node-test/node_modules/ejs/lib/ejs.js:272:36) at View.exports.renderFile [as engine] (/Users/nagafuji/Desktop/node-test/node_modules/ejs/lib/ejs.js:489:10) at View.render (/Users/nagafuji/Desktop/node-test/node_modules/express/lib/view.js:135:8) at tryRender (/Users/nagafuji/Desktop/node-test/node_modules/express/lib/application.js:640:10) at Function.render (/Users/nagafuji/Desktop/node-test/node_modules/express/lib/application.js:592:3) at ServerResponse.render (/Users/nagafuji/Desktop/node-test/node_modules/express/lib/response.js:1012:7) at Query.<anonymous> (/Users/nagafuji/Desktop/node-test/app.js:26:11) at Query.<anonymous> (/Users/nagafuji/Desktop/node-test/node_modules/mysql/lib/Connection.js:526:10)
回答1件
あなたの回答
tips
プレビュー