[英]How can I solve 'ENOENT' error in next.js api section?
I am woking on a Next.js Project and in there I need to read data using an api and for that I have created 1 api route in /pages/api
directory and that Api is using a function from `/store/manipulate.js' and I have imported that particular function in my api Route file but when I request on that api route it is giving me an error.我在 Next.js 项目上工作,在那里我需要使用 api 读取数据,为此我在
/pages/api
目录中创建了 1 个 api 路由,并且 Api 正在使用来自 `/store/manipulate.js 的函数' 并且我已经在我的 api 路由文件中导入了那个特定的函数,但是当我在那个 api 路由上请求时,它给了我一个错误。
So, the component below is requesting for data on that api route.因此,下面的组件正在请求该 api 路由上的数据。
Homepage.jsx主页.jsx
import axios from 'axios'
import { useEffect, useState } from 'react'
import EventList from '../components/events/EventList'
const HomePage = () => {
const [featuredEvents, setFeaturedEvents] = useState([])
useEffect(() => {
(async () => {
const res = await axios.get('/api/getfeaturedevents')
if (res.status(200)) {
console.log(res.data)
setFeaturedEvents(res.data)
return
}
console.log(res.status)
})()
}, [])
return (
<div>
<h1>
The Home Page.
</h1>
<EventList items={featuredEvents} />
</div>
)
}
export default HomePage
Now, the code shown below is the code of api route file现在,下面显示的代码是api路由文件的代码
getFeaturedEvents.js getFeaturedEvents.js
import { fetchFeaturedEvents } from '../../store/manipulate'
const getFeaturedEvents = (req, res) => {
if (req.method === 'GET') {
try {
const data = fetchFeaturedEvents()
res.send(data)
} catch (error) {
console.log(error)
res.status(500).send()
}
}
}
export default getFeaturedEvents
Now, let's take a look at manipulate.js which will just update store.json
present in same folder.现在,让我们看一下仅更新同一文件夹中存在的
store.json
的操作。
manipulate.js操纵.js
const path = require('path')
const fs = require('fs')
const readData = () => {
const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'store.json')))
return data
}
export const fetchFeaturedEvents = () => {
let data = readData()
const result = data.filter(event => event.isFeatured)
return result
}
Now, the Error I am getting is...现在,我得到的错误是......
Like you said @juliomalves I just changed my __dirname
to process.cwd()
in manipulate.js
file in readData()
method.就像你说的@juliomalves 我刚刚在
readData()
方法中的manipulate.js
文件中将我的__dirname
更改为process.cwd()
。
Something like this像这样的东西
const readData = () => {
const data = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'store', 'store.json')))
return data
}
就我而言,我删除了 pages 中的默认 API 文件夹
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.