Next.js Discord

Discord Forum

fetch database using api side in nextjs project

Unanswered
Checkered Giant posted this in #help-forum
Open in Discord
Checkered GiantOP
Hey, i cant find how to use database in api side, i shearch, i ask to ia and i try to find how but thats dont work, actually i have somethings like that : in my app/api/users/page.js
export default async function handler(req, res) {
  try {
    // const users = await User.findAll();
    res.status(200).json({text:'b'});
  } catch (error) {
    console.error('Error fetching users:', error);
    res.status(500).json({error:'error'});
  }
}

app/blog/page.js :
const [users, setUsers] = useState({text:'a'});

    useEffect(() => {
      const fetchUsers = async () => {
        try {
          const response = await fetch('/api/users');
          const data = await response.json();
          setUsers(data);
        } catch (error) {
          console.error('Error fetching users:', error);
        }
      };

      fetchUsers();
    }, []);

return (
  <h2>{users.text}</h2>
);


but i get one error :

27 Replies

Checkered GiantOP
if someone have an idea plz @ me
and i get this error in my log
@definitelynotshourya `res` is undefined
Checkered GiantOP
yep, but why?
do you know the reason ?
Yacare Caiman
um
I'd say the whole structure is wrong
as in your using the way api are written in pages folder, but in app folder
import { NextResponse } from 'next/server'
 
export async function GET(request: Request) {
  return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}
thats an example
@Checkered Giant
@definitelynotshourya https://nextjs.org/docs/app/building-your-application/routing/router-handlers follow this
Yacare Caiman
yeah that's what i was looking for haha
Checkered GiantOP
i can replace the
const res = await fetch('https://data.mongodb-api.com/...', {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY,
},
})
by my sequelize.findall?
@Yacare Caiman yeah that's what i was looking for haha
Checkered GiantOP
@definitelynotshourya i put my database but i keep geting this error :
my api code :
import { NextResponse } from 'next/server'
import Blog from '../../../module/sequelize/model/Blog'
 
export async function GET() {

  await Blog.findAll().then(x=>{
    return NextResponse.json({text:'Test',text2:x})
  })
 
  
}
maybe use axios instead of fetch
just put the api route and axios manages everything else for you
try calling the api through axios and get back to us
Checkered GiantOP
How can i use axios to find in my db?
@joulev const blogs = await Blog.findAll() return NextResponse.json(…)
Checkered GiantOP
Thats work but i dont understand somethings
in my db thats create a table "Blogs", but in my code i dont have "Blogs" i juste use "Blog"
const { DataTypes } = require('sequelize');
const sequelize = require('../sequelize');

const Blog = sequelize.define('Blog', {
  test1: {
    type: DataTypes.STRING,
  },
});

(async () => {
    await Blog.sync({force:true});
    console.log('table created !');
})();

module.exports = Blog;
i define 'Blog' but in my db i have
That one is on your db setup, i have no comments
Checkered GiantOP
I solve my db problme but i have to put paramettre in my fetch, i try this code :
const response2 = await fetch('/api/setUser',{
            method:'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ name: 'A', password: 'B' }),
          });
but i dont know what i have to change in my api file to put it in post, i try a code like that :
export default async function handler(req, res) {
    if (req.method === 'POST') {
      // Handle the POST request here
      const { body } = req;
      
      // Perform any necessary data validation or manipulation
      
      // Make the API call
      try {
        
        await Blog.create({
            title:'Test2',
        })

        NextResponse.json({text:'Test',text2:x})

        // res.status(200).json(data);
      } catch (error) {
        // Handle any errors that occur during the request
        res.status(500).json({ error: 'Something went wrong' });
      }
    } else {
      res.status(405).json({ error: 'Method not allowed' });
    }
}
but that dont work, do you know how can i make it?