#fetch database using api side in nextjs project

29 messages · Page 1 of 1 (latest)

zealous flume
#

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```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 : ```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 :

red creekBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)
zealous flume
#

if someone have an idea plz @ me

#

and i get this error in my log

slow sluice
zealous flume
#

do you know the reason ?

split violet
#

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

slow sluice
#

@zealous flume

split violet
zealous flume
#

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?

zealous flume
#

my api code : ```JS
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})
})

}

split violet
#

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

zealous flume
#

How can i use axios to find in my db?

stiff lodge
zealous flume
# stiff lodge const blogs = await Blog.findAll() return NextResponse.json(…)

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

stiff lodge
#

That one is on your db setup, i have no comments

zealous flume
#

I solve my db problme but i have to put paramettre in my fetch, i try this code : JS 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 : ```JS
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' });
}

}