React route pass-through - flask

I have a React-Typescript UI running on top of a flask API. I'm using BrowserRouter for routing paths in the UI. For a couple routes I want the react app to just fall back to rendering raw HTML returned by the underlying flask app. ie I don't want to map the route to an element, just fetch the route from the back-end. Is there some way to tell the route to behave this way?
Edit: Here's a detailed outline of the issue:
The react app is a thin client over top of a flask app. When requests come in the front door, the flask app either handles the request, or re-routes it to the react UI:
#app.route('/', defaults={'path': ''})
#app.route('/<path:path>')
def index(path):
if path.startswith("api/v0/"):
abort(404)
if current_user.is_authenticated and current_user.is_active:
return render_template("ui/index.html")
elif current_user.is_authenticated:
return render_template("inactive.html")
else:
return render_template("unauth.html")
The flask app has a /logout route, that unloads the current user and then redirects to the (flask-handled) / route, prompting unauth.html to load. This works fine when I directly navigate to /logout.
The React UI has its own router for loading page elements. Loading /ui/index.html launches the app, and it essentially defines its own namespace for rendering pages:
<Routes>
<Route path="" element={<Navigate replace to="/collections" />} />
<Route path="/" element={<App />}>
<Route path="home" element={<Home />} />
<Route path="collections">
<Route path=":collectionId" element={<CollectionDetail />} />
<Route index element={<CollectionsList />} />
</Route>
<Route path="users">
<Route index element={<UserList />} />
</Route>
<Route path="images/:imageId" element={<ImageDetail />} />
</Route>
<Route
path="*"
element={
<main>
<p>Page not found</p>
</main>
}
/>
</Routes>
The issue is I have no way to break out of the react app context once I'm in it. Specifically, placing a <Link /> to "/logout" takes the default route in the app and renders "Page not found". But if I navigate directly to /logout the flask app handles it correctly.
One solution might be to move all the html-generating flask responses to the react app, but I think this would complicate routing in the flask app itself- ideally flask is only aware of the single entry point to the react app at /ui/index.html

The Link component has a reloadDocument prop that can be used to "skip client side routing and let the browser handle the transition normally (as if it were an <a href>)". In doing so this a page request is made to the server and can be handled there.
See Link.
interface LinkProps
extends Omit<
React.AnchorHTMLAttributes<HTMLAnchorElement>,
"href"
> {
replace?: boolean;
state?: any;
to: To;
reloadDocument?: boolean;
}
Example:
<Link to="/logout" reloadDocument>Logout</Link>

Related

React Router DOM not working correctly on Amplify Console AWS

I have deployed react app on Amplify Console following their documentation. The site is deployed and running fine, I am able to navigate using links but when I try to land to any url directly I get redirected to my configured 404 page.
Below is the code I am using
ReactDOM.render(
<Router>
<Route path="/" component={App} />
</Router>,
document.getElementById("root"),
);
And here is how my route looks like -
<Switch>
<Route
exact
path="/"
render={(): JSX.Element => <Home auth={this.auth} />}
/>
<Route path="/features" render={(): JSX.Element => <Features />} />
<Route
path="/pagenotfound"
render={(): JSX.Element => <PageNotFound />}
/>
<Redirect from="/**" to="/pagenotfound" />
</Switch>
Here is the link to the app - https://master.dkf0zemoh330o.amplifyapp.com/features
I found that using these settings, as mentioned here and here.
i.e updating the redirect rule to these settings
Source address: </^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>
Target address: /index.html
Type: 200
Thanks!
I would add also |json| the string - it fixes "Manifest: Line: 1, column: 1, Syntax error on Chrome browser" problem:
Manifest: Line: 1, column: 1, Syntax error on Chrome browser

How to configure one URL Rewrite/proxy rules on IIS?

Architecture:
User --> ARR Server --> LB --> 2 Web Server serving 2 different sites
Web Server1 serving -> https://xxxx-green-xxxx-xxxx.net/xxx/xxx?xx=xxxx where green keyword comes in any place in domain name
Web Server2 serving -> https://xxxx-yellow-xxxx-xxxx.net/xxx/xxx?xx=xxxx where yellow keyword comes in any place in domain name
Requirement:
Request format: https://xxxx-green-xxxx-xxxx.net/xxx/xxx?xx=xxxx or yellow URL
In ARR we need to filter the URL with green and yellow keyword in URL and send it to respective Web Server IP.
But all my requests are landing to home page only. and even i am confused that whether changing the host will work but i need to give IP which is different for each web server in LB
We have set this Rule and getting below results:
<rule name="Green" enabled="true" stopProcessing="true">
<match url="(.*xxx.net)(/.*)" />
<conditions logicalGrouping="MatchAll"
trackAllCaptures="false">
<add input="{HTTP_HOST}" pattern="green" />
</conditions>
<action type="Rewrite" url="https://xx.xxx.xx.xx/{R:2}"
appendQueryString="true" />
</rule>
Where R:2 is --> xxx/xxx?xx=xxxx
As per your question.
You need to write Custom rewrite rule for that.
So first refer this link
Into link you can handle your requirement and rewrite to other other web server.
So please follow all the step and write you logic into
Rewrite(string value) method.
Into this method you need to pass your server url from IIS rules and check via condition like below.
public string Rewrite(string value)
{
if(value.Contains("green"))
{
return // your rewrite URL here
}
else if(value.Contains("yellow"))
{
return // your rewrite URL here
}
return value;
}
So it's working as per your requirement.

WCF 4 routing service throws handler error

I am trying to use WCF 4 routing declaratively to redirect one branch of my (REST) web services to an alternate server. I configured WCF's System.ServiceModel.Routing.RoutingService to route http://oldserver:81/FileService/ calls to http://newserver:82/FileService/, but when I try to access the redirected service, all it does is throw the error
Handler "HttpLogging" has a bad module "HttpLoggingModule" in its module list
I can enter URLs to the new service in my browser and they work fine, but URLs to the old service (to be re-routed) fail.
I have added the following routing configuration into my web service application:
<configuration>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior name="routingConfig">
<!-- Specify the routing table to use. -->
<routing filterTableName="routingTable1" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
<!-- WCF routing table -->
<routing>
<filters>
<filter name="FileFilter1" filterType="EndpointName" filterData="FileService"/>
</filters>
<filterTables>
<filterTable name="routingTable1">
<add filterName="FileFilter1" endpointName="FileService" />
</filterTable>
</filterTables>
</routing>
<client>
<!-- Destination endpoint defining the base URL where File messages will be routed. -->
<endpoint name="FileService"
address="http://newserver:82/FileService/"
binding="webHttpBinding"
contract="*" />
</client>
<services>
<!-- WCF routing service. -->
<service name="System.ServiceModel.Routing.RoutingService" behaviorConfiguration="routingConfig" >
<host>
<baseAddresses>
<!-- The service endpoint to be redirected. -->
<add baseAddress="http://oldserver:81/FileService" />
</baseAddresses>
</host>
<!-- Define the endpoints of the service to receive messages. -->
<endpoint name="reqReplyEndpoint" binding="webHttpBinding" contract="System.ServiceModel.Routing.IRequestReplyRouter" address="" />
</service>
</services>
There is no longer a FileService service in the application, except the one that should be exposed by the routing service.
I've tried:
filter types of MatchAll, EndpointAddress, and PrefixEndpointAddress;
various forms of the old service addresses;
different names for filters, routing tables, services;
renaming contracts.
None of it gets my client to call the redirected service, much less even any indication that the routing service is operational or even configured at all.
How do I make the routing actually work? Failing that, how would I debug it so I can determine what to fix?
The general problem I see is that you are trying to route REST calls with Routing Service, which is not supported. MSDN reference:
https://msdn.microsoft.com/en-us/library/ee517423.aspx
The Routing Service does not currently support routing of WCF REST
services. To route REST calls, consider using System.Web.Routing or
Application Request Routing
(http://go.microsoft.com/fwlink/?LinkId=164589).
Blockquote

Setting up Mock Endpoints in Apache Camel with log:*

I have several routes that end with a log uri such as
<route>
<from uri="someUri" />
<to uri="someProcessor" />
<to uri="log:SOME_LOG?level=INFO" />
</route>
I am using CamelSpringJUnit4ClassRunner to run my unit tests.
I want to be able to mock my log endpoints as MockEndpoint objects. I have tried to use
#MockEndpoints("log:*")
along with
end = MockEndpoint.resolve(camelContext, "log:SOME_LOG?level=INFO");
but that generates a ClassCastException cannot cast InterceptSendToEndpoint to MockEndpoint.
and also tried
#EndpointInject(uri="log:SOME_LOG?level=INFO")
MockEndpoint end;
but that also generates an IllegalArgumentException.
Invalid type: org.apache.camel.component.mock.MockEndpoint which cannot be
injected via #EndpointInject/#Produce for: Endpoint[log:SOME_LOG?level=INFO]
A workaround I've found is by prepending my log uri with "mock:" and using
#EndpointInject(uri="mock:log:SOME_LOG?level=INFO) and defining my route in xml with
<route>
<from uri="someUri" />
<to uri="someProcessor" />
<to uri="mock:log:SOME_LOG?level=INFO" />
</route>
However I would like to get this to work by mocking my log: uris and not having to modify my route definitions in camel.xml.
Is there something that I'm missing?
When you use #MockEndpoints("log:*"), the camel just create the mock endpoint for you, the mock endpoint uri should be mock:log:THE_REMAINED. You should be able to get the mock endpoint with below code:
end = MockEndpoint.resolve(camelContext, "mock:log:SOME_LOG?level=INFO");

ASP.Net login control will not work with Intelligencia.UrlRewriter

I hope someone can help me shed some light on this nightmare I'm having...!
I have just complete an ASP.Net e-commerce website with the help of an Apress book; The BalloonShop project, some of you might already know the one.
Everything is fine and dandy apart from one niggle that I cant seen to sort out!
I cannot logout from my site using the asp.net login control from any page that does not have the .aspx extension in the Url. This is namely; Departments, Category and Products as these are using the Intelligencia.UrlRewriter to provide browser friendly url's.
My url's are rewritten perfectly, but when I try to logout from a page that is using the url rewriter it does not work, and I receive the following message in my error log email:
Exception generated on 22 February 2013, at 22:23
Page location: /Triple-x/Dynamo-p4/?
<div id=":143">ProductId=4
Message: The HTTP verb POST used to access path '/Triple-x/Dynamo-p4/' is not allowed.
Source: System.Web
Method: System.IAsyncResult BeginProcessRequest(System.Web.HttpContext, System.AsyncCallback, System.Object)
Stack Trace:
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSt ep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)</div>
In my web.config if have:
<configSections>
<section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler,Intelligencia.UrlRewriter" />
</configSections>
<rewriter>
<!-- Rewrite department pages -->
<rewrite url="^.*-d([0-9]+)/?$" to="~/Catalog.aspx?DepartmentID=$1" processing="stop" />
<rewrite url="^.*-d([0-9]+)/page-([0-9]+)/?$" to="~/Catalog.aspx?DepartmentID=$1&Page=$2" processing="stop" />
<!-- Rewrite category pages -->
<rewrite url="^.*-d([0-9]+)/.*-c([0-9]+)/?$" to="~/Catalog.aspx?DepartmentId=$1&CategoryId=$2" processing="stop" />
<rewrite url="^.*-d([0-9]+)/.*-c([0-9]+)/page-([0-9]+)/?$" to="~/Catalog.aspx?DepartmentId=$1&CategoryId=$2&Page=$3" processing="stop" />
<!-- Rewrite product details pages -->
<rewrite url="^.*-p([0-9]+)/?$" to="~/Product.aspx?ProductId=$1" processing="stop" />
</rewriter>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
<remove name="ScriptModule" />
<!--<add name="ScriptModule" preCondition="managedHandler" />-->
</modules>
</system.webServer>
I am also using IIS7 on my local machine, and have read that this can sometimes be the cause re: AppPool version. I have tried changing this to Classic ASP as suggested, but this did not work for me!
Does anyone know if this is a common problem when hosting on local machine and using Intelligencia.UrlRewriter? Would this possibly not be an issue if hosting on a shared web hosting server?
If I'm way off the mark then please forgive my naivety, as I am still quite new to this, especially projects of this size.
Thanks for you help!!
If you want to use url rooting you can use this codes. I use it also an e-commerce project:
in Global.asax file :
void Application_Start(object sender, EventArgs e)
{
if (RouteTable.Routes.Count <= 0)
{
RouteTable.Routes.Add("Urun", new Route("Urun/{category}/{name}/{prid}/{caid}", new PageRouteHandler("~/ProductDetail.aspx")));
RouteTable.Routes.Add("Kategori", new Route("Kategori/{upper}/{name}/{caid}", new PageRouteHandler("~/Categories.aspx")));
RouteTable.Routes.Add("Icerik", new Route("Icerik/{name}/{cpid}", new PageRouteHandler("~/ContentPage.aspx")));
}
}
And you can this codes wherever you want to give link:
var param = new RouteValueDictionary
{
{"category", "Oyuncak"},
{"prid", ((DiscountProductsResult) e.Item.DataItem).ProductId},
{"name", ((DiscountProductsResult) e.Item.DataItem).UrlView.Replace(" ", "-")},
{"caid", 0}
};
VirtualPathData path = RouteTable.Routes.GetVirtualPath(null, "Urun", param);
And you can get querystring values like this:
RouteData.Values["caid"]