Returned data being rendered instead of page structure in Nuxt - vue.js

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

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/

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

Related

How to bypass router for certain URLs with Vue Router?

I'm using Vue Router with Vue 3 in a web application I'm working on, and have a 'catch all' route defined as the last route:
{
path: "/:catchAll(.*)*",
component: () => import("pages/Error404.vue")
},
This is picking up everything, though, including calls to the /api/ back end (although not via Ajax), and even things like '/test.csv', which is a link to a CSV file in the root directory.
How can I bypass the router for certain URLs, allowing them to be treated as regular requests?
Incidentally, I don't know whether this is relevant, but the application in question is a PWA built using Quasar. When I make the call to e.g '/test.csv', I see a request for 'service-worker.js' with a 304 response code in my nginx access log, confirming that the request is being handled by the router rather than nginx.

Allow API routes in Vue Router?

I'm working on a Vue 3 app (using Quasar) with Vue Router. I want the user to be able to click on certain links (with paths beginning '/api/') which bypass the router completely and go straight to the backend API. But everything is getting picked up instead by the catch-all route (path: "/:catchAll(.*)*"). I tried adding a route without a matching component, path: "/api/*", but that doesn't work.
Is there a way for me to tell the router to ignore certain paths and let them be handled by the server?

Is there a way to redirect a NuxtJs application using Express server?

I have a NuxtJs application initialized with Express server using npx create-nuxt-app <project-name>. It is set for server-side rendering.
Express has access to NuxtJs middleware like so. ( Which comes by default when Nuxt app is created )
app.use(nuxt.render)
Now I have created a different route file in server side that handles API routes. This route works as I can access data using Axios. I have added this route right before the above code, like this. ( API routes don't work if it is added after )
app.use('/api', apiRoutes)
app.use(nuxt.render)
There is a route where, after some operation, I need to redirect the application to another page. I tried using res.redirect('/some-route'), which is an Express way for redirection but that didn't work.
Am I missing something here? Is there some other way we do redirection from server side in Nuxt application that I'm totally unaware of?
Finally found the way to redirect from the back-end.
res.writeHead(301, { Location: url })
res.end()
Here is the link to Nuxt GitHub issue comment for detailed example using server middleware.
Alternatively, you could respond with desired value to the font-end and based on the value received, you can re-direct from the front-end.

Vue direct URL is not working, only router-link click

This may be a known Vue routing thing that I am totally missing.
So I have a .vue file that uses the url /hardware.
Here is the routing
{
path: "/hardware",
name: "Hardware",
component: () =>
import(/* webpackChunkName: "hardware" */ "../views/Hardware.vue")
},
Going to /hardware directly using a link on an external site or typing it in the address bar does not work, gives me Page Not Found.
But clicking on this link in my nav bar does work.
<router-link to="/hardware">Hardware</router-link>
Am I missing something super obvious that I missed when I was learning routing? Is this because it is a single page application? Thanks in advance for any help.
Adding that I do have history mode on, wondering if this is the issue?
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
Following back from comments to answer (Netlify) Vue-router works locally and not at the hosting/deployment side like Apache/Nginx/Firebase Hosting as:
1)
Pretty-URL / Hashbang dilemma in SPA.
The server needs to redirect when your Vue project enabled history mode. in apache, just some redirect rules needed to be done via .htaccess similarly, so as most of the hosting services included Netlify (you need to check the routes redirect rules at Netlify there). As server page not found, telling us that your route doesn't have actual files under that specified /route at their side.
Previous thread: Vue Router return 404 when revisit to the url
2) If your project for Multi-page-mode instead of going hashbang SPA, Your Vue Project needed to be configured little bit further: Either via SSR or pre-rendering static files before deployment
It could be that your browser is adding a trailing slash to giving you "/hardware/" which does not match your route. In the past, I had created an alias to match both routes such as "/hardware" and "/hardware/".
I faced the same issue nowadays and decided to share my thoughts with the community.
You can easily resolve the bug just by removing mode: "history" from the Router. Then it will be automatically replaced by the hash (#) in your URLs. It's going to work then even if you'll use a direct link in the browser.
However, based on the latest SEO recommendations History mode is more preferable because URLs without # are better tracked by Google.
If you would like to save History mode, you need to enable history mode on your server. I use Express middleware and the solution in my case is next:
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static('src'));
app.get('/', (req, res) => {
res.sendFile('src/index.html');
});
app.listen(3000, () => console.log('server started'));

Using Swagger for Express alongside normal routes

I'm interested in using something like swagger-node-express to build the API for the project I'm working on. However, some parts of the app are non-api based (serving HTML instead). Has anyone got any ideas as to how I would use Swagger alongside normal routes?
You'll just need to make sure that your routes don't conflict with the Swagger routes, and your other routes will processed as usual. One easy way would be to make Swagger live under a subpath. Take a look at the docs on that score:
https://github.com/wordnik/swagger-node-express
var app = express();
var subpath = express();
app.use(express.bodyParser());
app.use("/v1", subpath);
swagger.setAppHandler(subpath);
Otherwise, you could just keep an eye out to make sure that none of the other URLs you are using in your application conflict with the Swagger URLs, and you should be able to define your routes and handlers normally. E.g. you can use Swagger to serve up docs under http://localhost:8002/api-docs.json/pet but have http://localhost:8002/foo/ do something else just by adding the route in the normal way:
app.get(/foo/, function(req, res, next) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Foo\n');
})
Using the subpath configuration is probably the cleanest approach but you could also just keep track of the routes yourself and make sure that the Swagger routes aren't conflicting with the routes in the rest of your app.