Next.js のapiをaxiosで叩き、データベース内のデータを取得しようとしたところ Cannot read property 'findByPk' of undefined エラーが発生。
javaScript
1//pages/api/user.js 2const db = require('../../db/models/'); 3 4export default (req,res) =>{ 5 db.User.findByPk(1) //ここでエラー発生 6 .then(usr=>{ 7 res.status(200).json({usr}); 8 }) 9}
javascript
1//pages/index.js 2import axios from 'axios'; 3import React,{useEffect,useState} from 'react'; 4 5const Home = () => { 6 const [data,setData] = useState(''); 7 8 useEffect(()=>{ 9 axios.get('/api/user') 10 .then(usr=>{ 11 setData(usr.name); 12 }) 13 }) 14return( 15 <div> 16 <p>Hello</p> 17 <p>{data}</p> 18 </div> 19) 20} 21 22export default Home; 23
javascript
1//models/index 2'use strict'; 3 4const fs = require('fs'); 5const path = require('path'); 6const Sequelize = require('sequelize'); 7const basename = path.basename(__filename); 8const env = process.env.NODE_ENV || 'development'; 9const config = require(__dirname + '/../config/config.json')[env]; 10const db = {}; 11 12let sequelize; 13if (config.use_env_variable) { 14 sequelize = new Sequelize(process.env[config.use_env_variable], config); 15} else { 16 sequelize = new Sequelize(config.database, config.username, config.password, config); 17} 18 19fs 20 .readdirSync(__dirname) 21 .filter(file => { 22 return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); 23 }) 24 .forEach(file => { 25 const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); 26 db[model.name] = model; 27 }); 28 29Object.keys(db).forEach(modelName => { 30 if (db[modelName].associate) { 31 db[modelName].associate(db); 32 } 33}); 34 35db.sequelize = sequelize; 36db.Sequelize = Sequelize; 37 38module.exports = db;
json
1//package.json 2{ 3 "name": "nextsequelize", 4 "version": "0.1.0", 5 "private": true, 6 "scripts": { 7 "dev": "next dev", 8 "build": "next build", 9 "start": "next start" 10 }, 11 "dependencies": { 12 "axios": "^0.21.1", 13 "next": "10.1.3", 14 "react": "17.0.2", 15 "react-dom": "17.0.2", 16 "sequelize": "^6.6.2", 17 "sequelize-cli": "^6.2.0", 18 "sqlite3": "^5.0.2" 19 } 20}
<エラー文>
TypeError: Cannot read property 'findByPk' of undefined
at module.exports../pages/api/user.js.webpack_exports.default (C:\Users\name\Desktop\nextsequelize.next\server\pages\api\user.js:187:11)
at apiResolver (C:\Users\name\Desktop\nextsequelize\node_modules\next\dist\next-server\server\api-utils.js:8:7)
<ファイル構成>
.next
node_modules
db
-config
-migrations
-seeders
-models
ーuser.js
ーindex.js
-db.sqlite3
page
public
styles
package.json
package-lock.json
<試したこと>
https://github.com/dyarfi/nextjs-sequelize
を参考にコードを書き換えてみたりしたが、解決できず。
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー