Jdsans
Jdsans

Reputation: 194

Returned data being rendered instead of page structure in Nuxt

I'm trying to return data as JSON from the express server for a route. The data returns fine but when i open the NUXT page on the browser than the JSON data gets outputted instead of the page HTML.

Note the express route is the same as the page route. I know the routes are conflicting with each other. Do i need to have the server and front-end on different ports? Is there anything wrong i'm doing here?

Thanks

Upvotes: 3

Views: 674

Answers (2)

Ilijanovic
Ilijanovic

Reputation: 14914

To avoid conflicts such as that you should use a prefix like /api/ or /api/v1/ something like that

In nuxt.config.js you need to define your server middleware

serverMiddleware: ["~/api/index.js"]

That file is your server. At the bottom you need to export it like this:

module.exports = {
   path: "/api",
   handler: app
}

Note here: app is your express app if you use express.js.

This here: const app = express();

If everything worked your root of your API should be available under host:port/api/

Upvotes: 1

TEFO
TEFO

Reputation: 1653

you cant do this if the routes for backend and frontend exactly same. this is route rules that they have to be unique and its not backend or frontend issue for e.x. you can have two routes with same url in express(api), nuxt too.

if we say the application for example is post office, the route are path to a house address (controller or action) so we can have two path to get the a house but its confusion have a same path(url or route) and different houses.

simple solutions:

  • as you said make the api and front separate with different ports or different domains or even have a prefix for your express routes
  • in express handle all of them, means return view or page with data needed instead of json data

Upvotes: 0

Related Questions