Vue-router not finding direct routes when deployed in Netlify - javascript

I have deployed an app in Netlify, the link is: https://www.fluento.net. The website is working correctly, but whenever I try to access for example https://www.fluento.net/start, I get 404 error. If I go to the root url and press on the Start button, I get correctly redirected to https://www.fluento.net/start.
I have searched online and saw it might be a problem with history mode but I can't seem to figure out how to solve the issue.
This is the configuration of the router:
const routes = [
//Some routes in here, 404 not set!
]
const router = createRouter({
history: createWebHistory(),
routes
})
I have seen some solutions to add some configuration to nginx and so on, but my app is deployed in Netlify automatically when pushing to github, so I do not have any nginx configuration file or anything.
Also, I have seen that adding a catch all route and redirecting to index could work (as explained in the vue docs), but it didn't work for me, or maybe I did it wrong. But then again, I do not want to redirect to index, I want to redirect to the correct website according to the URL. And having a catch all means that for any 404 I would be redirecting to the index (which I don't want to do).
Another weird thing I found, is that whenever I type: https://www.fluento.net/privacy or https://www.fluento.net/tos I can reach those pages. This is the view that serves them:
<template>
<iframe src="/tos.html"></iframe>
</template>
<style scoped>
object, iframe {
border: none;
height: 800px;
width: 100%;
min-height: calc(100vh - 125px);
}
</style>
Maybe not having any javascript makes those two routes work? Not sure, because the App component that calls them has some javascript already.
EDIT: For everyone in the same situation, I managed to find a fix. Not setting this as an answer because I don't really understand how this works, and can't explain it. But following this answer Vue Router return 404 when revisit to the url in another question, this is how to implement this in Netlify:
At the end of the routes file in Vue, add this route to catch all the unknown routes and send them to an error page.
{
path: '/:pathMatch(.*)*',
name: 'error404',
component: Error404
}
The error page could be a view like this:
<template>
<p>Not found</p>
</template>
And then create a file in the folder that will be public after the build command is executed. In my case npm run build builds my project and adds the content of public/ folder to the root of the website. So I added a file public/_redirects that will be added in the root of the website.
For example, if my website is https://mywebsite.com, there will be a https://mywebsite.com/_redirects file. This file is not accessible, but Netlify understands and will "compile".
public/_redirects:
/* /index.html 200
This is the part that I am not sure what it does, but please if someone could explain in the comments it would be great. But I think it redirects all the traffic from uncaught urls to the index with the original URL and then the index executes the vue-router.
This is it, if you look for an URL you don't catch in vue-router you should see the 404 page, otherwise you should see the correct view.

Related

Different slug names for the same dynamic path stackoverflow, redirect Nextjs

I have a project that has links for categories and products (see below) and I have to rewrite the project using nextjs, but I have to keep the links (it's important for SEO)
root:
[category] # e.g.: https://domen.com/categoryslug-category-id-103
[product] # e.g.: https://domen.com/productslug-product-id-3663267
But we know that nextjs doesn't allow you to have more then one dynamic page in the same folder.
I understood that with nextjs methods it's impossible (e.g. redirects in next.config.js). Or possible?
I thought about making just one general dynamic page (e.g. [dynamic]) and using different conditions to handle different links/pages in this page, but it will be very big file and it seems not good practice. (I haven't yet tried it, it was just idea, bad idea I guess)
Maybe I have to have the traditional nextjs structure:
root:
category:
[categorySlug] # e.g.: https://domen.com/category/categoryslug-category-id-23
product:
[productSlug] # e.g.: https://domen.com/product/productslug-product-id-3663267
and then somehow to 301 redirect from https://domen.com/category/categoryslug-category-id-23 to https://domen.com/categoryslug-category-id-23, but how?
Just in case: I use Django REST framework as a backend.
Maybe the only way is to get rid of Next.js and use just React? I am newbee and don't now whether it will be possible to have this flexibility with row React AND it's crutual if it's possible to set ssr, ssg without next.js using jast React and if so, how? But would want to remain with Next.js because it has a lot of good fiatures for SEO from the box. But the sake of handling my issue I am ready to get rid of Next.js :(
I heard that it can be done by NGINX (I don't plan to use Vercel server, at least for now I don't think about it). If I have only this option, can you give me a tip/link how to do it.
By this link https://github.com/vercel/next.js/issues/9130 I maybe found the solution (by BramDecuypere), but I don't understand one: "What we do now though (for blogs at least), is have them come from our CMS and store the alternate links of the blogs inside the page as well. So we know there is always a link we can refer too."
What would you do if you had the same task/issue?
I used middleware:
https://nextjs.org/docs/advanced-features/middleware#conditional-statements
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
export function middleware(request) {
if (request.nextUrl.pathname.includes("category-id")) {
const [slug] = request.nextUrl.pathname.split("-");
return NextResponse.rewrite(new URL(`/category${slug}`, request.url));
}
if (request.nextUrl.pathname.includes("product-id")) {
const [slug] = request.nextUrl.pathname.split("-");
return NextResponse.rewrite(new URL(`/product${slug}`, request.url));
}
}
when you access https://domen.com/categoryslug-category-id-103, it will use /category/[categorySlug] page
the url is still https://domen.com/categoryslug-category-id-103
Then, to avoid duplicates, I wrote in next.config.js the appropriate 301 redirects
to redirect from links like /category/[categorySlug] to like https://domen.com/categoryslug-category-id-103

React router V4 / V5 / V6 nested routing 404 net::ERR_ABORTED 404,

I have tested everything described below with both react router V4 and V5. In V4 the error is just 404, but in V5 it also includes net::ERR_ABORTED.
I am creating a React app with React router. I need to have a /test route and /test/:param1/:param2 route.
First route is OK, but when I created the second and navigated the browser to localhost:8080/test/something/something2 I received a blank page with error in the console saying that it failed to GET localhost:8080/test/something/index.js.
I am using webpack and webpack-dev-server. I then tested more:
Tried to put the second route inside the component of the first.
Tried simplifying the route to /test/:param1, but that didn't work either.
I then tried just a normal 1 level nested route /test/test2(no parameters) and still got the error in the title.
I have also configured a 404 page, however it is displayed only if the path is 1 level: /{something that does't exist}. If I navigate to /{something}/{something more} I get the same ERR_ABORTED.
For some unknown to me reason the browser tries to GET /test/index.js, which obviously doesn't exist.
I spent a day looking through articles, tutorials, and the react router documentation, but everywhere nested routes just work. In fact there is absolutely nothing about this error.
Edit1: After some more testing I've been able to narrow down the issue to just one question: How to configure react-router to always look for the bundle at {domain, localhost:port}/index.js?
Edit2: Tested it with the beta of V6 - same result.
Another is to check if you have in the Webpack config the following:
output: {publicPath: '/'},
Took me some time.
After a few hours I finaly figured it out!! The mistake was so dumb. In my index.html file I required the bundle with <script src="./index.js"></script>. Simply removing the dot fixed the issue. If somebody has the same error, first check your index.html.

Configure routing

I have created a sample app using #RouteConfig and it working fine. See the url changes and view added according to configuration, but when I am refreshing the page it's showing a 404 error.
I am using WebStorm IDE to build and run the app.
The same problem happens with given live example on angular.io.
I have downloaded the sample code example for routing and navigation in AngularJS2 on https://angular.io/resources/live-examples/router/ts/plnkr.html which given on angular.io and opened the project into WebStorm and ran it.
It working fine but after doing some routing and then refreshing the page it shows a 404 Error.
Angular 2 (in default) uses html5 pushState for router states. Which means actual url changes between states.
For example for home page you may be in url: / and you click something, your address becomes /newAddress. This is done using pushState api and pure frontend. But if you refresh page, server tries to render the resource on /newAddress but, of course, there is no such resource on server. You need to configure your server to host / whatever the url is, but I don't know if it is possible or not in WebStorm internal server. You can install and use superstatic npm package.
OR... You can configure Angular 2 to use hashbang based urls (such as /#/ and /#/newAddress). That way, you hit / every time from perspective of backend.
This page has detailed explanation.
Make sure you've included a
<base href="/">
in your head section. Aside from that, we're going to need more information.
This will solve your problem, add this to your bootstrap
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
bootstrap(AppComponent,[ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy })]);
Now whenever you hit a refresh or a hard reload the default component defined in #RouteConfig would be loaded.
in your AppComponent :
#RouteConfig([
{path: '/login', name : 'Login' , component : Login , useAsDefault: true}
])

How to get my 404 page to show after upgrade of Sails.js to 0.10.x?

I've upgraded my Sails.js app to 0.10.x and now when I point my browser at a non-existent route such as http://localhost:1337/notfound instead of my views/404.jade being served up I just get a bit of JSON
{
"status": 404
}
I built a default new sails app sails new dummy --template=jade just to compare and contrast with what I have in my existing app, and the only obvious difference I see is that in dummy/config/ there is a file called http.js
I've copied that file over to my app but it's made no difference.
I've also ensured that the tasks in dummy/tasks are identical to my own app's tasks.
In dummy/config/routes.js it says
Finally, if those don't match either, the default 404 handler is triggered.
See config/404.js to adjust your app's 404 logic.
Which is obviously out of date as 0.10.x apps use the api/responses mechanisms.
So I am at rather a loss as to how to get this to work.
I am using 0.10.0-rc8 (and I have confirmed that this is the same in my dummy app as well as my actual app)
Well I've fixed this but I have no idea why it was happening.
To fix it I created a new project as per the method described in my question, but with the same name as my existing project, then, file-by-file, I painstakingly moved across everything specific to my app, taking care to leave in place anything new generated by sails.
Once I'd done that I ran my tests - all passed - and then sails lift and tried it, and yay, everything worked and I got my 404 error page back.
I committed my changes and then carefully picked through a comparison of what had changed.
Alas nothing at all stands out, so, while I have solved my problem, I have no idea what the original cause was.
From the section in the migration guide on "Custom Responses":
In v0.10, you can now generate your own custom server responses. See
here to learn how. Like before, there are a few that we automatically
create for you. Instead of generating myApp/config/500.js and other
.js responses in the config directory, they are now generated in
myApp/api/responses/. To migrate, you will need to create a new v0.10
project and copy the myApp/api/responses directory into your existing
app. You will then modify the appropriate .js file to reflect any
customization you made in your response logic files (500.js,etc).
Basically, v0.10.x gives you more freedom in how things like res.notFound, res.serverError and even res.ok() (success response) work, but you need to copy over the new api/responses folder to migrate.
I had the same issue but was using 0.9.x. Probably a better solution but I outputted a view instead of JSON in all cases.
Update config/404.js to replace res.json() with res.view():
if (err) {
//return res.json(result, result.status); }
return res.view('404') // <-- output the 404 view instead
}
Then, just make sure in your routes.js file it will redirect the /404. Place the following at the bottom of your routes.js file:
'/*': {
view: '*'
},

Backbone Router root duplicates in the url

I've just finished developing my first Backbone app and I detected a small quirk with the Router which I don't seem to be able to fix.
My routes look like this:
routes: {
'': 'index',
'jobs/:id': 'viewJob',
'*default': 'notFound'
}
It works fine when serving the app from the server root, but it doesn't when I serve it from a subfolder. In that case I always get the default route.
I though adding the root param to the backbone history would do the trick so I added it like this:
Backbone.history.start({ pushState: true, root: '/subdir/' });
With this the app seems to load as expected but the Router is automatically adding the root to all the routes and it ends up being duplicated, so when I first visit the website:
http://mysite.com/subdir/
It loads the app and changes it to this:
http://mysite.com/subdir/subdir/
This makes the app to break when reloading the page or using the browser back button as that route doesn't really exist.
What would be the approach to avoid this? I don't want to hardcode the folder name in the routes as it might change or be served from the root.
UPDATE: I've just realized I was adding the duplicated folder name myself using router.navigate somewhere in my code. I just removed it and everything works as expected.
Just a small guess.. do you really want pushState turned on? This can cause problems on reload if the server is not setup to serve out of the new directory.

Categories

Resources