Blazor Relative url - iis

I have navlink defined as follows
<NavLink href="/intro"></NavLink>
In dev it works fine as the root of the site is at the same level as the blazor app.
In prod I have to put the blazor site inside a folder in the default iis website.
So my url becomes something like this
http://something/apps/cor/
So the <NavLink href="/intro"></NavLink> ends up trying to go to http://something/intro instead http://something/apps/cor/intro
I tried both /intro and intro and the both result in the wrong behavior. I am not getting how to make those links relative to blazor root not iis root.

Dot before the path. ./intro is how you do it

on index.html you should have <base href="/apps/cor/" />

I had to do this trick in _Layout.cshtml:
#inject IWebHostEnvironment Environment;
// in <head> :
#if (Environment.IsDevelopment())
{
<base href="~/" />
}
else
{
<base href="~/myApp" />
}
then either <NavLink href="page"></NavLink> or <NavLink href="./page"></NavLink> works.
On localhost: https://localhost:44393/page
On server: https://example.com/myApp/page

Related

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

This is a PERN app. I don't remember ever getting this error and I haven't found any records when doing a Google search.
I don't see anything wrong in the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<!-- <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> -->
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Any idea where it comes from? I get it as soon as I start the app.
I'm just a beginner but it happens when you are passing the wrong URL to the fetch function, suppose that your db.json file is running on port 8000 and you are passing port 3000, that's why.
useFetch("http://localhost:3000/blogs/" + id);
Instead, try this, it might helps. :)
useFetch("http://localhost:8000/blogs/" + id);
Hope it helps.
So I had this same error when I installed npm gh-pages. My solution was to delete the Homepage link in package.json and it worked.
I had the same problem .
If you are using node server, install this npm install body-parser
and add these lines in your server-side code
const bodyParser = require("body-parser"); router.use(bodyParser.json());
I'm new at this, but I found if I added a proxy to my package.json (client side, not server side) it worked! It looks like this in package.json (placed above my dependencies): "proxy": "http://localhost:3001", . I believe it's because the client side can't read it, and the proxy tells it to pass it to the server side which can read it.
I got the same error while deploying the React app on Vercel. Turns out, I forgot to add environment variables to the project settings on Vercel.
Check if you are calling your api prefixing the protocol, like this 'https://apiurl...', not like this 'api.something'
Faced the same issue and it was my json path was incorrect. Initially it was fetch('./movies.json') which was incorrect path.
Fix it and now working fine:
useEffect(() => {
fetch('../movies.json')
.then(res => res.json())
.then(data => setMovies(data.posts))
}, [])
I was trying to fetch data from the backend into my react application, with out mentioning the proper path of the url in the loader function of the react-router library, hence this issue occured and once I defined the correct path, it worked just fine.
const response = await fetch("http://localhost:8080/events");
I forgot to mention "events" in the url.

The <base href="./"> was not working in index.html

Whenever I am using <base href="./"> in my index.html file it was showing the following error
Error: The base href in "web/index.html" must be absolute (i.e. start with a "/"), but found: `<base href="./">`.
after rectifying the error and using <base href="/"> the content was not rendering on the screen later I also remove the <base> tag but it doesn't work.
How to specify the current directory in <base> tag without proving the full relative path?
Add <base href="/"> this line instead of <base href="$FLUTTER_BASE_HREF"> this solved the problem for me
if not run the flutter clean command and try to run

IIS Router Site rewrite rule doesn't find resource file when accessed with resource /current

On my IIS I have configured rewrite rules in the following way.
There is a Router Site which listens on port 80 and rewrites to proper websites by specified resource e.g when user enters host http://testpage.com/current it rewrites it to another website hosted under port 5001. Sample config:
<rule name="RewriteRule" stopProcessing="true">
<match url="^current(.*)?" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
<action type="Rewrite" url="http://{HTTP_HOST}:5001/{R:1}" />
</rule>
The site hosted under 5001 contains index.html and javascript file index.js which is referenced in index.html like this:
<script type="text/javascript" src="/index.js">
The entire configuration works super fine when I replace
<match url="^current(.*)?" />
with
<match url="^(.*)?" />
However when I use current here then it finds index.html located in page hosted under port 5001 but it can't find index.js. I suspect that the reason is because it tries to find /current/index.js but it doesn't exist.
I always thought that my RewriteRule should basically rewrite url to
http://testpage.com:5001
then get index.html and resolve index.js from current directory so it shouldn't have any knowledge about "current" resource.
Is there an easy way to fix this?
Obviously when I enter to the website like this: http://testpage.com:5001, bypassing rewrite rules it works fine.
I'll answer this for my future reference. It's not an issue with rewrite rules. The issue is with the way html resolves resources.
We need to do a few steps:
Set <base href="virtualpath">, in this example virtualpath should be equal to /current. We use webpack during TeamCity deployment to put correct value here. Example:
<script type="text/javascript">
window.virtualpath = window.location.pathname.toLowerCase().indexOf("${virtual_path_legacy}") >= 0 ? "/${virtual_path_legacy}" : "";
document.write("<base href='" + window.virtualpath + "/'/>");
</script>
new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") }, virtual_path_legacy: JSON.stringify(virtual_path_legacy) })
In webpack.config.js make sure your publicPath is "" instead of "/"
If you use SignalR make sure you pass your virtualpath to $.hubConnection(If SignalR is hosted under virtualpath)
in .NET Core:
app.UseAppBuilder(appBuilder => appBuilder.MapSignalR(rootPath, hubConfiguration), camelCaseSerialization);
If you use react-router make sure you pass virtualpath to useRouterHistory. Example:
const browserHistory = useRouterHistory(createHistory)({
basename: infoService.virtualpath,
});
If you use libraries like fetch to connect to the API make sure to prefix all your api urls with virtualpath (if your API is also using virtualpath)

React.js website build works on one host, but not another

I am new to react.js . I have created a react website using create-rect-app. I have run: npm run build in git and got my static site files. Everything works on the test host, however when i moved hosts only index page works and navigating to other page gives 404 error. For routing im using react-router-dom.
How can i get my page to work on the other host?
Working host: http://000webhost.com/
Badly working host is some local provider
Edit: Basically i have pages such as /Home and /Contact.
Im using react-router-dom.
code:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import logo from './logo.svg';
import './App.css';
import Home from './pages/Home.jsx';
import Contacts from './pages/Contacts.jsx';
import Our_products from './pages/Our_products.jsx';
class App extends Component {
render() {
return (
<Router>
<div>
<Route exact path ="/" component={Home}/>
<Route exact path ="/Home" component={Home}/>
<Route exact path ="/Contacts" component={Contacts}/>
<Route exact path ="/Our-products" component={Our_products}/>
</div>
</Router>
);
}
}
export default App;
My index is linked to /Home as you can see from code. i have uploaded Build folder to public_html on both hosting platforms. On one site works normaly, on the other only /Home page shows up.
So, you can ignore this, but what helped is changing
<a href="/" />
to
<Link to="/" />
. Basically one hosting provider could render links as
<a />
other only as
<Link />

Angular 2 in dev and production with IIS and webpack

I'm building an Angular 2 web application that communicates with webapis to get data, the app will be hosted on IIS with Windows authentication and I have some questions :
Should I use system.config as the main examples of Angular 2 work with?
If so, what about production and how can I work with sass?
Should I use webpack as angular-cli? If so, how can I combine with the advantages of the webpack Dev server (Hot reloading, sass trans-pilers, etc.)
and IIS hosting with Windows authentication?
Sorry if the questions are irrelevant but I'm a .NET developer and new to Angular 2 and Webpack.
You can use the angular-cli to develop the angular 2 app. To deploy the app on production on IIS you can use:
ng-build --prod command from angular-cli command prompt to build the app. This will generate the files required for deployment in dest folder. These are just HTML, javascript, css and other assets that your app uses.
You can copy contents of dest folder and deploy in folder of your IIS web application.
Note:
Angular 2 routing (with hash) will work without any issue on IIS. Just create default URL rewrite rule which will redirect all the requests to index.html file of your angular app. Rule will redirect all requests to index.html except for required js files and actual angular app urls (i.e. index.html or index.html#/{route-value}.
EX: <rules> <rule name="Default"> <match url="(.* ).js|index.html(.*)" negate="true" /> <action type="Rewrite" url="/index.html" /> </rule> </rules>
Angular 2 routing (without hash) will not work with IIS. In case of pure HTML application IIS will be routing the incoming request and it will redirect the request to error page if such page does not exist at that location.
In case of .Net MVC application you can create a default route to handle all the incoming request url's and redirect it to your angular index view.
Ex Route for MVC application:
routes.MapRoute(
name: "Angular",
url: "{*url}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { url = new AppFeatureUrlConstraint() }
public class AppFeatureUrlConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values[parameterName] != null)
{
var url = values[parameterName].ToString();
if (url.StartsWith("angular/", StringComparison.InvariantCultureIgnoreCase))
return true;
else
return false;
}
return false;
}
}
I recommend Angular cli with webpack. It has hot module reloading already integrated and has out of the box development and production environments with bundling and tree shaking functionality.

Resources