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.
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,
},
};
}
I am having a CORS issue with Ionic 3 when attempting to make GET calls to an API. I am using Ionic local server, running ionic serve in the command line for live server.
Error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not
allowed access.
I tried updating ionic.config.json with proxy setting but that does not seem to be working..
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games/"
}
]
}
My Data Service
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class DataProvider {
headers = new Headers({'user-key': '1234567890123'});
options = new RequestOptions ({headers: this.headers});
limit: number = 50;
constructor(public http: Http) {
console.log('Hello DataProvider Provider');
}
getGames(genre, offset_num) {
let genre_id = genre;
let offset = offset_num;
return this.http.get('https://api-2445582011268.apicast.io/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
}
}
I am trying to make calls to this api
Request Url
https://api-2445582011268.apicast.io
HEADERS
Key Value
user-key YOUR_KEY
Accept application/json
Primary Question
My calls are failing. How do I create proxy for this issue?
To fix this issue, please change the following lines
ionic.config.json
{
"name": "projectLeagueApp",
"app_id": "47182aef",
"type": "ionic-angular",
"integrations": {
"cordova": {}
},
"proxies": [
{
"path":"/games",
"proxyUrl": "https://api-2445582011268.apicast.io/games"
}
]
}
You have to remove the " / " which is at the end of of "proxyUrl".
My Data Service
return this.http.get('/games/?fields=name,release_dates,screenshots&limit='+this.limit+'&offset='+offset+'&order=release_dates.date:desc&filter[genres][eq]='+genre_id+'&filter[screenshots][exists]', this.options)
In the http call, the url should begin with '/games'. '/games' because ionic will proxy http://localhost:<port>/games to https://api-2445582011268.apicast.io/games
Please use the above method for external GET and POST calls in your application.
Thank you.
If you wan to use for testing in Chrome just install chrome extension
Allow control origin
Quick and easy way
To test in development environment, you can run Google Chrome in disable-web-security mode.
Steps to follow (On Windows)
Press Windows Key + R to open Run window.
Enter/input following command and press Enter key.
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Steps to follow (On Ubuntu)
Kill all the chrome.exe instances before you run/execute it.
chromium-browser --disable-web-security --user-data-dir="[some directory here]"
Before Chrome 48
chromium-browser --disable-web-security
Steps to follow (On Mac)
Run following command in terminal.
open -n -a "Google Chrome" --args --user-data-dir=/tmp/temp_chrome_user_data_dir http://localhost:8100/ --disable-web-security
the proxy functionality expects that you're referencing the local server. in your GET request, you're still pointed at the remote API. If you change your code to this.http.get('/games/...' it should start to function as the request will go to http://localhost:8100/games..., which the "proxy" option will catch and pass on to the URL you've provided.
You may also only need to put https://api-2445582011268.apicast.io in the proxyUrl field. I think the rest of the path is passthrough.
My CORS issue got FIXED when I updated Android System Webview from the play store.
I tried Cordova-Advance-HTTP Plugin but my PUT Request was not working with Cordova-Advance-HTTP plugin.
After Updating Android System Webview I used HTTP Client plugin which I was using before. Updating Android System Webview helped me in CORS issue
```
export function getAuthHttp(http: Http, options: RequestOptions) {
console.log("token",storage.get('id_token'));
return new AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'bearer',
tokenName: 'id_token',
tokenGetter: (() => storage.get('id_token')),
noJwtError: true,
//globalHeaders: [{'Accept': 'application/json'}],
globalHeaders: [{'Content-Type':'application/json'},{"Access-Control-Allow-Origin": "*"}],
}), http, options);
}
```
You can handle the CORS when debugging in browser by using CORS extension or by disabling the security of Chrome.
But you need to handle the CORS when you debug in app on the server side, I was consuming woo-commerce API ,so i edited it as follows->
1.Plugins->editor->woocomerceapi
right after
<?php**
header(“Access-Control-Allow-Origin: *”);
2.Update File
I just want to make VS Code's debugger work with webpack-dev-server without ignoring my breakpoints.
Now, webpack-dev-server serves the bundled files from memory, while, if I understand this correctly, the VS Code debugger searches for them on disk (...or not?...)
As a result, whenever I set a breakpoint I get the dreaded
Breakpoint ignored because generated code not found (source map problem?)
Now, every related question I could find had to do with typescript mostly, and not with the fact that webpack-dev-server serves from memory. I am not using typescript. Seems that people are either not using webpack-dev-server, or I am missing something blatantly obvious, with my money on the latter.
This is my VS Code launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceRoot}",
"sourceMaps": true,
"trace": true
}
]
}
and these are the related lines from my webpack.config.js
devtool: 'cheap-module-source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js'
},
I have tried various modifications to the launch.json to no avail, so I am just pasting it in vanilla form.
Note that the output.path is only used when there is a production build and the files are spewed to disk.
Here is what the structure of the files is in the served page:
And here is the command I am running in development
"scripts": {
"start": "webpack-dev-server --host 0.0.0.0 --config ./webpack.config.js"
},
Finally, here is a relevant chunk from the trace file
From target: {"method":"Debugger.scriptParsed","params":{"scriptId":"30","url":"http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js","startLine":0,"startColumn":0,"endLine":150,"endColumn":57,"executionContextId":2,"hash":"216099518F33D6091EC12795265804FB35669A30","executionContextAuxData":{"isDefault":true,"frameId":"18228.1"},"isLiveEdit":false,"sourceMapURL":"manifest.0ec68ebd5f0abf9b4cd4.js.map","hasSourceURL":false,"isModule":false,"length":5906}}
Paths.scriptParsed: could not resolve http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js to a file under webRoot: e:\Mitch\Workspace\Projects\project-name. It may be external or served directly from the server's memory (and that's OK).
SourceMaps.getMapForGeneratedPath: Finding SourceMap for http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js by URI: manifest.0ec68ebd5f0abf9b4cd4.js.map and webRoot: e:\Mitch\Workspace\Projects\project-name
SourceMaps.loadSourceMapContents: Downloading sourcemap file from http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js.map
To client: {"seq":0,"type":"event","event":"script","body":{"reason":"new","script":{"id":1,"source":{"name":"manifest.0ec68ebd5f0abf9b4cd4.js","path":"http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js","sourceReference":1001}}}}
To client: {"seq":0,"type":"event","event":"scriptLoaded","body":{"path":"http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js"}}
SourceMap: creating for http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js
SourceMap: sourceRoot:
SourceMap: sources: ["webpack:///webpack/bootstrap 7617f9bf7c8b0bc95159"]
SourceMap: webRoot: e:\Mitch\Workspace\Projects\project-name
SourceMap: no sourceRoot specified, using webRoot + script path dirname: e:\Mitch\Workspace\Projects\project-name\
SourceMap: mapping webpack:///webpack/bootstrap 7617f9bf7c8b0bc95159 => webpack\bootstrap 7617f9bf7c8b0bc95159, via sourceMapPathOverrides entry - "webpack:///*": "*"
SourceMaps.scriptParsed: http://localhost:8080/manifest.0ec68ebd5f0abf9b4cd4.js was just loaded and has mapped sources: ["webpack\\bootstrap 7617f9bf7c8b0bc95159"]
From my experience (about 15 mins ago), if 'webpack.config.js' has a value for the context property, then that has to be accounted for for '.vscode/launch.json'.
For an example, if 'webpack.config.js' has the following:
module.exports = {
context: path.resolve(__dirname, 'src'),
entry: './index.ts',
Then launch.json needs that context ('src') too:
"url": "http://localhost:8080/",
"webRoot": "${workspaceRoot}/src",
"sourceMaps": true,
I just updated/fixed my repo so now TypeScript breakpoints should bind.
https://github.com/marckassay/VSCodeNewProject
For Webpack 4:
Install webpack-cli locally if you don't already have it installed (it has been pulled out of webpack).
Add the following VSCode debug configuration to your .vscode/launch.json (that's the file that VSCode opens when you click on the wheel icon in Debug view):
{
"type": "node",
"request": "launch",
"name": "build",
"program": "${workspaceFolder}/node_modules/.bin/webpack-cli",
"args": [
"--config",
"webpack.config.prod.js"
],
"autoAttachChildProcesses": true,
"stopOnEntry": true
}
stopOnEntry will make debugger stop in the very first (shebang) line of webpack.js, like this:
Old thread, but it still comes up in searches...
It feels like turning on "writing the generated code to disk" might be the solution here:
As per https://webpack.js.org/configuration/dev-server/#devserverwritetodisk-, add this to webpack.config.js:
module.exports = {
//...
devServer: {
writeToDisk: true
}
};
If in case someone troubling with start-server-webpack-plugin of webpack:
I have recently stuck on the same issue and #MarkoBonaci's answer came to rescue. However, I stuck on another error which is produced by the webpack plugin: start-server-webpack-plugin.
Below is the error I got, when I launched by application via debugger of vscode:
cd /home/me/projects/villager-topics ; env "NODE_ENV=development"
/home/me/.nvm/versions/node/v11.6.0/bin/node --inspect-brk=33538
node_modules/.bin/webpack-cli --colors --progress --config
./webpack.dev.js Debugger listening on
ws://127.0.0.1:33538/d8bb6d64-a1a1-466e-9501-6313a3dc8bcf For help,
see: https://nodejs.org/en/docs/inspector Debugger attached.
clean-webpack-plugin: /home/rajeev/projects/villager-topics/dist has
been removed. 10% building 1/1 modules 0 active webpack is watching
the files…
98% after emitting StartServerPluginStarting inspector on
127.0.0.1:33538 failed: address already in use
As you can see StartServerPlugin is using the same port 33538 which is already taken by the parent process. So we need to tell StartServerPlugin to use some other port for its inspection initialization. This, we can achieve through the initialization of StartServerPlugin.
new StartServerPlugin({
name: 'server.js',
nodeArgs: ['--inspect=5858'], // allow debugging),
})
Here in nodeArgs we are specifying the inspect port as 5858. After this configuration is saved and then relaunch the application through Debugger of vscode, you will successfully start the application.
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);
}
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.)