I would like to add "/app" as my base path for all routes in react routes. So I am trying -
.... more routes
I am unable to make webpack dev server serve pages with URL localhost:8080/app. It gives me a "Cannot get /app" error. If I try localhost:8080/ - it gives me an error that it cannot match a route with "/".
What should be a basic webpack dev server configuration for this scenario?
The Webpack historyApiFallback config option is what you're looking for. Just set that to true and all requests that don't route to an asset will be rewritten to /. You can also pass in an object with custom rewrites:
historyApiFallback: {
rewrites: [
{ from: /^\/$/, to: '/views/landing.html' },
{ from: /^\/subpage/, to: '/views/subpage.html' },
{ from: /./, to: '/views/404.html' }
]
}
(Example taken from the documentation page linked above.)
Related
I am building a project using NextJs and Vercel, but, when the users try to access a new page or route, the Vercel gives them the 404 error.
In other projects, I used Netlify as router and this error was fixed using the netlify.toml config file, but, I am not able to do the same using the vercel.json file.
Can you guys help me to turn this file:
netlify.toml
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Into a vercel.json config file?
I was trying with this settings:
vercel.json
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html"}]
}
But it did not solved my issue.
A workaround is to use a catch all route that immediately redirects to the index page. For example:
// [...404].jsx
export default function Page() {
return null;
}
export function getServerSideProps() {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
Here's my svelte.config.js and I'm using adapter-static :
const config = {
kit: {
adapter: adapter({
// default options are shown
pages: '../backend/build',
assets: '../backend/build',
fallback: null,
precompress: false,
}),
alias: {},
appDir: '_app',
browser: {
hydrate: true,
router: true,
},
files: {
assets: 'static',
hooks: 'src/hooks',
lib: 'src/lib',
params: 'src/params',
routes: 'src/routes',
serviceWorker: 'src/service-worker',
template: 'src/app.html',
},
floc: false,
methodOverride: {
parameter: '_method',
allowed: [],
},
paths: {
assets: '',
base: '',
},
trailingSlash: 'always',
vite: {
server: {
proxy: {
'/api': 'http://localhost:5555',
},
},
},
},
preprocess: null,};
From the backend (Go lang) I'm serving build directory & index.html file. The homepage works fine but whenever I click on any route, it sends get request to the server instead of redirecting in the app itself.
Here's the go code to serve from backend:
router := gin.Default()
router.StaticFile("/", "./build/index.html")
router.StaticFS("/_app", http.Dir("build/_app"))
I have also tried with the following code:
router.NoRoute(func(c *gin.Context) {
path := c.Request.URL.Path
c.File("./build/index.html")
})
Note: Things work fine when I run npm run preview.
The adapter-static has two distinct modes of operation: SPA and prerendering. When there are several routes, both the npm run dev and npm run preview works as intended, but once built, the static routing falls to the web server, in your case, the Go framework, but the same happens with any other static server (I have tested also Nginx and Apache).
I found a workaround to avoid converting the site to a SPA: Installing a url rewrite mechanism as a middleware in order to add the .html extension that the static server is expecting in the compiled site. In my case, I used Go Fiber github.com/gofiber/rewrite/v2 and it worked as intended (the same behavior as when using npm run dev)
For Nginx static server the solution is the same url rewrite and it could be used as explained here: https://www.codesmite.com/article/clean-url-rewrites-using-nginx
The homepage works fine but whenever I click on any route, it sends get request to the server instead of redirecting in the app itself
SvelteKit users internal router, or $app/navigator for links only if it detects a link to be the same domain as the current page. Likely your web server is misconfigured and there is a mismatch of domain somewhere in
The web browser address bar
Web server configuration
However, the question do not contain these details and is thus unanswerable "why" and how to fix it.
I set up a very basic Vue.js app essentially using these steps. When I added the router to this project, it asked whether I wanted to use History Mode and I said yes.
Now I am trying to implement the corresponding server configuration changes aka "add[ing] a simple catch-all fallback route to [the] server" but I'm not sure how to do this since I'm using Vercel for my deployments and from my understanding it's managing the server for me.
It seems like I'm able to do some configuration in Vercel, and I'm thinking maybe I need to configure a redirect like in their firebase.json example? If so, would my vercel.json just look like this?
{
"redirects": [
{ "source": "**", "destination": "/index.html" }
]
}
As per Vercel's vercel.json routes upgrade guide, SPA Fallback section, use this on your vercel.json file:
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
In my case I'm also using Vercel Serverless functions, so I also need rewrites for the /api routes, and here the order is important, it must be done this way:
{
"rewrites": [
{ "source": "/api/(.*)", "destination": "/api" },
{ "source": "/(.*)", "destination": "/index.html" }
]
}
Generally, Vercel automatically detects your configuration and sets it up so that all traffic points at your index.html file. That's kind of their big selling point.
If you want more explicit control, you could use the configuration shown in the Caveat section of the Vue docs you first linked to. Just create a simple component that redirects to the homepage and point * to it.
import NotFound from '../components/NotFound.vue'
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFound }
]
})
export default {
name: 'NotFound',
template: `<div></div>`,
mounted() {
this.$router.push({ path: '/' })
}
}
You are right, Vercel manages the server for you and you can configure vercel through a vercel.json file. In that vercel.json file you can define rewrite rules as you already assumed. The correct format for this is shown here in the docs of vercel.
Since you want to add a match all rule which directs to the base of your path, adding the following to your vercel.json should work:
{
"rewrites": [{ "source": "/:path*", "destination": "/index.html" }]
}
Explanatory extras:
The :path basically symbolizes a placeholder and the * makes sure it doesn't just match one subpath deep but everything that follows after the initial slash.
For example without the * after /:path you would match domain.xyz/foo but not domain.xyz/foo/bar.
Furthermore since it's a named placeholder you can reuse the matched path for the destination like so "destination": "/index.html/:path".
Which shouldn't be necessary for a frontend application like vue which uses the route inside the browser, but could be helpful for serverless functions.
In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.
And I want to read in the data by axios library in an event handling function inside the component of component-A as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)
In Vue-cli project, axios can't get data from custom folder.
You should use static folder to save test json file.
So you should change axios call like this:
axios.get('/static/service_general_info.json');
This will get data from json.
If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json
For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}
When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},
I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}
You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}
I am very new to Angular and running into an issue while trying to get a local .json file via http.get. This is due to my routing rules but I'm not sure how to fix it.
Directory Structure:
api
mockAppointments.json
app
app.component.*
scheduler
scheduler.component.*
scheduler.component.ts where http.get() call is made:
getAppointments() {
return this.http
.get('api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}
Routing rules:
const appRoutes: Routes = [
{
path: 'scheduler',
component: SchedulerComponent
},
{
path: '',
redirectTo: '/scheduler',
pathMatch: 'full'
}
];
As I browse to http://localhost:4200/scheduler, the page loads as expected but dev console has the error:
GET http://localhost:4200/api/mockAppointments.json 404 (Not Found)
When I try to get to that URL by typing it in the browser, I see the following in dev console:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL
Segment: 'api/mockAppointments.json'
So it's clear that the issue is with routing. For now I need all URLs redirected to /scheduler (which is happening). When I make a http.get('api/mockAppointments.json') call, it should just serve that as is, almost like a pass through. Everything I have looked at, I would need a component to go along with any routing rule. That is fine, but there wouldn't be a template associated with it.
I have tried putting the api folder under assets but it made no difference.
Eventually the api call would be external to the app so this wouldn't be an issue but how do I get it working during development?
TLDR: Is it possible to have a 'pass through' route which serves a JSON file as is via http.get() ?
copy your api folder into assets folder. Angular can only access files from assets folder.
getAppointments() {
return this.http
.get('assets/api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}