[Fixed] Skip express js view for API routes

Issue

I have my API and Website in same Express Js Project and needs to use ejs view for the website only. But not for the API to return JSON for API routes.

const app = express();

// For static website
app.use(express.static(path.join(__dirname, "public"), { 
  extensions : ['html']
}));

// API Routes
const bookRoutes = require("./routes/event.route");
app.use("/v1/books", bookRoutes);

// Website
// Set the view engine for dynamic header, footer on website
const ejs = require('ejs');
app.set('view engine', 'ejs');

API

/v1/books

Website

/index.html

How can I skip the view engine for my API routes and apply to /public folder only or even for selected files?

Error message, when I open /v1/books in Postman

{"message":"Failed to lookup view \"C:\\Users\\admin\\github\\test-app\\public\\v1\\books\" in views directory \"C:\\Users\\admin\\github\\test-app\\views\""}

The JSON was expected for /books API

{
 id : 1,
 name : 'book name'
}

Solution

For starters, routes are matched in the order you declare them. So, if you put this first:

// API Routes
const bookRoutes = require("./routes/event.route");
app.use("/v1/books", bookRoutes);

first, then it will get processed before it tries to match any of the static routes. But, this really shouldn’t be an issue because there shouldn’t be any files in your public folder that would match a request for /v1/books/xxx anyway.

As for the error for /v1/books, you will have to show us what the code is for bookRoutes. It appears that error is coming from that router. express.static() does not make errors like that.

How can I skip the view engine for my API routes and apply to /public folder only or even for selected files?

The app.set('view engine', 'ejs'); line just configures what view engine will be used if/when some code calls res.render(). There’s nothing happening with the view engine on one of your API requests because you should never be calling res.render() in an API route. You are presumably calling res.json() instead.

You should ONLY have files in your public folder that you want express.static() to match. That’s how you control it. Don’t put something in that folder that shouldn’t be served statically.

Leave a Reply

(*) Required, Your email will not be published