node.jsexpresscorsmern

Why the fetch gets failed even when I am using cors dependency?


Used just simple code which works properly fine as I have checked using localhost, but when I am trying to fetch the localhost from google console then the error is showing :

fetch('http://localhost:3500/'); PromiseĀ {} VM42:1 GET http://localhost:3500/ net::ERR_FAILED (anonymous) @ VM42:1 VM42:1 Uncaught (in promise) TypeError: Failed to fetch at :1:1

    const express = require("express")
const app = express();
const path = require("path");
const cors = require("cors")

const { logger } = require("./myMiddleware/logEvent");
const errorHandler  = require("./myMiddleware/errorHandler");

const PORT = process.env.PORT || 3500;

//custom middleware
app.use(logger);

app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(express.static(path.join(__dirname, "/public")));

app.use('/subdir', require('./routes/subdir'))
app.use('/', require('./routes/root'));


app.all('*', (req, res)=> { // page not found
    res.status(404)
    console.log("Thank You")
    if(req.accepts("html")) {
        res.sendFile(path.join(__dirname, "views", "404.html"));
    }else if(req.accepts("json")) {
        res.sendFile({ error : "404 not found"});
    }else {
        res.type("txt").send("404 not found");
    } 
});


// CUSTOM ERROR HANDLER
app.use(errorHandler);

app.listen(PORT, ()=> {
    console.log("Server running on port "+PORT); 
});



    

enter image description here


Solution

  • You seem to have SPA, so the problem is that you're actually serving 404 to fetch once the index.html is loaded.

    The usual way for SPAs is to send index.html on each request for the SPA's router to handle it. Also, API routes handlers should be set before that (for fetch to handle users and other data).

    Try this.

    // setup API routes for frontend router (users, get data and other stuff..)
    //app.use('/api', apiHandlers);
    
    // serve SPA on all routes
    app.get('/', (req, res)=> {
        res.sendFile(path.join(__dirname, "views", "index.html"));
    });
    
    // handle error
    app.use((err, req, res, next)=>{
        res.status(404).sendFile(path.join(__dirname, "views", "404.html"));
    });