fetch a route-handler with fs.readdirsync
Unanswered
Monsoon posted this in #help-forum
MonsoonOP
Hi, i'm newbie in web development and i've been trying make a way to fill out a array with the filenames of images in a folder. Searching for that, i tried to use a route handler following tutorials in internet, but i don't know why this don't work.
Fetch request gives me a '405' error.
Here is my code and a screenshot of the 405:
route handler (in the path: app/api/Slider/route.ts):
page.tsx in path app/page.tsx
the Slider tag prop images is a array of the image that the carousel use.
I read something about SWR but i don't know how to use it.
i'll be so thankful if you help me.
Thanks
Fetch request gives me a '405' error.
Here is my code and a screenshot of the 405:
route handler (in the path: app/api/Slider/route.ts):
import { NextApiRequest, NextApiResponse } from 'next'
import fs from 'fs'
import path from 'path'
export default (req: NextApiRequest, res: NextApiResponse) => {
const namefolderrelative = "img";
const dirimages = path.resolve('./public', namefolderrelative)
const nombreimagenes = fs.readdirSync(dirimages)
const images = nombreimagenes.map(name => path.join('/', namefolderrelative), name)
res.statusCode = 200;
res.json(images);
}page.tsx in path app/page.tsx
'use client'
import "./PaginaPrincipal.css"
import Slider from "./Componentes/carousel"
import { useState, useEffect } from "react";
export default function Home() {
const [images, setimages] = useState([])
useEffect(() => {
const fetchdata = async () => {
const response = await fetch('./api/Slider');
const data = await response.json();
setimages(data.imagenes);
}
fetchdata();
}, []);
return (
<div className="container-pagina">
<Slider images={images} AutoPlay={true}/>
</div>
)
}the Slider tag prop images is a array of the image that the carousel use.
I read something about SWR but i don't know how to use it.
i'll be so thankful if you help me.
Thanks