Home > Software engineering >  Node Js Serving react js frontend In Production No Such File directory
Node Js Serving react js frontend In Production No Such File directory

Time:10-18

Why I get No such a file index.html error

My Folder Structure

enter image description here

here is my Code in server.js.

    const PORT = process.env.PORT || 8000
    const express = require('express');
    const path = require('path')
    const http = require('http');
    const cors = require('cors');
    const app = require('./app.js');
    const planetsRouter = require('./routers/planets/planet.router')
    const { loadPlanetsData } = require('./models/planets.model')
    
    const server = http.createServer(app)
    app.use(cors({ origin: 'http://localhost:3000' }))
    app.use(express.json())
    app.use(express.static(path.join(__dirname, '..', 'public')))
    app.get('/', (req, res) => {
        console.log('Res', req)
        res.sendFile(path.join(__dirname, '..', 'public', 'index.html'))
    })
    app.use(planetsRouter)
    async function startServer () {
    
        await loadPlanetsData()
        server.listen(PORT, () => {
            console.log(`Listening on ${PORT}...`)
        })
    }
    
    startServer()

I got this error Error: ENOENT: no such file or directory, stat 'C:\Users\kullanıcı\Desktop\Node Js\24-Nasa-Project\server\public\index.html'

enter image description here

This is server.js

CodePudding user response:

If you're getting the error:

Error: ENOENT: no such file or directory, stat 'C:\Users\kullanıcı\Desktop\Node Js\24-Nasa-Project\server\public\index.html'

That means you don't have a file at the path:

C:\Users\kullanıcı\Desktop\Node Js\24-Nasa-Project\server\public\index.html

Just looking at that path, I notice: Users\kullanıcı\Desktop ... that looks like a path from your computer. But you're saying this is on your server ... does your server actually have that folder?

What could be going on is you could have hard-coded that path somewhere in your code during development, and then when you try to use it on your server, it fails because your server doesn't have that path. It doesn't seem possible from the code you provided, but could there be any other code you didn't share?

Alternatively, I noticed you had:

res.sendFile(path.join(__dirname, '..', 'public', 'index.html'))

Why the '..'? It seems your server.js is in your server project root folder, so .. would mean one folder above that .. but the public folder is in the same directory as server.js.

CodePudding user response:

I found the solution I made mistake while writing client package.json it was like this

I have Change it to the this enter image description here

There is a space after server/public if ı do like first picture I need to write public joint to && symbol

  • Related