route function from Preact-Router does not update window location or component - browser-history

I am trying to use the route function from preact-router in order to sanitize a hash prefix that I add. However, the route function does not seem to update the window location or the component that is rendered by the Router. Am I using this function wrong?
I am hosting my react build in an S3 bucket and using their redirecting rules to add a #! in between the base url and the path. Would using hash history instead of browser history and what are the downsides of hash history?
documentation
import { Router, route } from 'preact-router';
import Header from './header';
// Code-splitting is automated for `routes` directory
import Home from '../routes/home';
import Profile from '../routes/profile';
import Library from '../routes/library';
import LibraryCreator from '../routes/libraryCreator';
/**
* Removes the #! injected into the url
* A #! is prefixed to all requests sent to our S3 instance so that we send the index no matter what path is requested
* This allows the Router component to handle Routing and prevents 404/403 errors from requesting files which don't exist
* [More Info](https://via.studio/journal/hosting-a-reactjs-app-with-routing-on-aws-s3)
*/
const sanitizeHashPrefix = () => {
const path = (/!(\/.*)$/.exec(location.hash) || [])[1];
if (path) {
route(path, true);
}
}
const App = () => (
<div id="app">
<Header />
<Router onChange={sanitizeHashPrefix()}>
<Home path="/" />
<Profile path="/profile/" user="me" />
<Profile path="/profile/:user" />
<Library path="/library/:library" />
<LibraryCreator path="/library/newLibrary" />
</Router>
</div>
)

Related

Unmatched requests entered in the URL don't hit the backend

I have an app with frontend and backend. The user can login and sign up and perform CRUD operations. All of the requests defined in the backend are hitting the api. However, some unmatched requests that the user enters in the search bar like: https://myapp.com/foo/bar/foo/bar/ don't hit the backend (I am trying to redirect all such requests by using app.all() by appending it to the end of all the routes in the app). When I enter an unmatched request in the backend api directly, it returns the correct response. SS attached below:
However entering an unmatched from the frontend does nothing. In the network request tab, this is what I see. The request type is document and initiator is other. Also, the request is not logged at the backend. How to solve this issue?
Routes:
import express from 'express'
import { userSignUp, userLogin } from '../controller/userController.js'
const router = express.Router()
router.post('/login', userLogin)
router.post('/signup', userSignUp)
export default router
import express from 'express'
import authorization from '../middlewares/authorization.js'
import {
createTest,
getAllTest,
getSingleTest,
deleteTest,
updateTest,
} from '../controller/workoutController.js'
const router = express.Router()
// router.use(authorization)
//Get everything
router.post('/getAll', getAllTest)
//Get a single workout
router.get('/:id', getSingleTest)
//Post a new workout
router.post('/', createTest)
//Delete a single workout
router.delete('/:id', deleteTest)
//Update a single workout
router.patch('/:id', updateTest)
export default router
server.js file
import dotenv from 'dotenv'
dotenv.config()
import express from 'express'
import morgan from 'morgan'
import workoutRoutes from './router/workout.js'
import userRoutes from './router/user.js'
import mongoose from 'mongoose'
import cors from 'cors'
import multer from 'multer'
import rateLimit from 'express-rate-limit'
import SlowDown from 'express-slow-down'
const app = express()
const upload = multer()
app.use(upload.array())
//get the response in json
app.use(express.json())
//using morgan to log requests
app.use(morgan('dev'))
//using cors to make fetch requests
app.use(cors())
//routes
app.use('/api', userRoutes)
app.use('/api', workoutRoutes)
app.all('*', (req, res) => {
res.status(400).send({ message: 'Invalid Route' })
})
//connect to DB
mongoose
.connect(process.env.MONG_URI)
.then((data) => {
app.listen(process.env.PORT, () => {
console.log('Listening on Port', process.env.PORT)
})
})
.catch((err) => {
console.log(err)
})
Edit 1: Was checking my console.log and saw this console.warn logged for the routes that are unmatched. My best guess now is that react-router is not letting the request hit the api.
SS attached for reference.
I have found the answer and posting this for future geniuses. This goofy question exists because of my lack of understanding of react-router.
I am using react-router and basically inside the browser window all of the routing is handled by the react-router. So, when you hit a path in the address bar, the react router first checks it's routes if that path exists. If it does, the component that exists at that path is rendered (the request is NOT sent to the backend. Requests only reach the backend when a component at that path renders and uses fetch or any other api to get data). Otherwise, it looks for a handler for that path which you can set up using *. Example:
<Routes>
<Route path="/" element={<Homepage />} />
<Route path="/:id" element={<SingleBlog />} />
<Route path="/createBlog" element={<CreateBlog />} />
<Route path="/:id/edit" element={<EditBlogs />} />
<Route path="/signup" element={<SignupForm />} />
<Route path="/login" element={<LoginForm />} />
<Route path="*" element={<Page404 />} />
</Routes>
This path with * will serve every url that the react-router does not recognize(This does not mean you shouldn't have a check in the backend. Imagine a person modifiying the request and sending it to the backend). A request is sent to the backend using fetch or axios or any other api. When a page is rendered, you will probably have set up apis to fetch you data from the backend and if that route doesn't exist in the backend then you need to set-up a handler in the backend to catch it and send a response to the user.

Nuxt - login without redirect

I'm trying to create authentication on my Nuxt app, but every tutorial I've found is using redirect to public / private paths.
Example:
if (user.isLoggedIn()) {
redirect('/dashboard')
} else {
redirect('/login')
}
I'm used to react way, where I have a single wrapper component in which I decide by the state if I want to show public (login) or private (dashboard) page.
Example of index page (route path '/'):
export default = ({ viewer }) =>
viewer.isLoggedIn ? <Dashboard /> : <Login />
Is there any way to achieve this in Nuxt?
You have to set a dynamic layout parameter in your Page.vue files.
first step, set dynamic layout in your Page.vue:
export default {
layout (context) {
return context.isLoggedIn ? 'privateLayout' : 'publicLayout';
}
}
second step, set a Context custom var (or better, in your Store) from a middleware auth:
export default function (context) {
context.isLoggedIn = true; //or false, insert your auth checking here
}
see documentation: https://nuxtjs.org/api/pages-layout#the-layout-property
see live example: https://glitch.com/edit/#!/nuxt-dynamic-layouts?path=pages/index.vue:10:8
You can use your index page as a wrapper for two components that show depending on whether the user is logged in. So inside your index.vue:
<template>
<div class="wrapper">
<dashboard v-if="userIsLoggedIn" />
<login v-else />
</div>
</template>
Then you could write the dashboard and login component as separate pages and even switch dynamically between them by making userIsloggedIn reactive.
Hope that's more like what you're looking for.

react router server side rendering: How to get route params on server side?

OK, I'm still trying to build react.js app with server side rendering. I having big time dealing with react-router with parameters. I cannot extract routes params from route on server side to make proper query on DB.
Here is my react-router route:
import {Router,Route} from "react-router";
import React from "react";
import App from "../components/app";
import {HomeContainer} from "../components/home";
import {TagContainer} from "../components/tag";
export function createRouter(hist) {
const routes = <Route component={App}>
<Route path="/" component={HomeContainer}/>
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
</Route>;
return (
<Router history={hist}>{routes}</Router>
);
}
the route run fine until I add parameter ":unique_name" to the route
<Route path="/tag/:unique_name" name="tag" component={TagContainer}/>
on the server side, I cannot extract unique_name from the route to make query on DB:
Here is the route on server(Using Node.js & Express.js):
const router = express.Router();
router.get("/tag/:unique_name", ServerRenderController.tagRender);
server.use(express.static(path.join(__dirname, '..', '/build')));
server.use(router);
and here is my "ServerRenderController.tagRender":
function tagRender(req, res) {
console.log(req.params.unique_name);
/*
output :
mytag_unique_name -> this is the route params
style.css ->stylesheet - how the hell it become route params?
app.js -> client code - how the hell it become route params?
vendor.js -> vendor scripts - how the hell it become route params?
manifest.js -> manifest file -how the hell it become route params?
*/
match({browserHistory,routes, location:req.url}, (err, redirectLocation, renderProps)=> {
if (redirectLocation) {
//#TODO: response redirect location
console.log('redirect location');
}
if (err) {
//#TODO: response error
console.log(err.stack);
}
if (!renderProps) {
//#TODO: route to 404
console.log("no renderProps");
}
renderPage(renderProps); // return HTML to client with __PRELOADED_STATE__
}
Questions :
What did I do wrong in server code (routing, express static
middleware...).
How do I extract correct route params from route? (I only want to extract "mytag_unique_name" as the only params when I browse to http://localhost/tag/mytag_unique_name)
right now the route params including static files that should be
send as MIMETYPE css/js.
OK. Turn out I made mistake in references to style sheets and scripts file.
In the server render code must refer <link href="/style.css" rel="stylesheet"/>
with slash (/) at the begining of the rel attr.
Note here for anyone have same problem.

How to send GET/POST requests using express and react router?

I currently have express set up to serve a static html page where my react components mount to. I'm also using react router because I have nested routes. For example:
I have an App component (green outline). Within that component, I'm rendering a Header component (orange outline) and a Footer component (red outline) and passing in a Review component (blue outline) through this.props.children.
My server.js file (express):
const express = require('express');
const app = express();
app.use(express.static('dist'));
const PORT = process.env.PORT || 3000;
app.listen(PORT, function() {
console.log(`Listening on port ${PORT}...`);
});
My routes.js file (react-router):
import React from 'react';
import ReactRouter, {
Router,
Route,
browserHistory,
IndexRoute,
} from 'react-router';
import App from '../components/App';
import Home from '../components/Home';
import Review from '../components/Review';
import Game from '../components/Game';
const routes = (
<Router history={browserHistory}>
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="/game/:id" component={Game} />
<Route path="/game/:id/review" component={Review} />
<Route path="*" component={Home} />
</Route>
</Router>
);
export default routes;
My question is, I want to be able to make GET/POST requests (GET from the Game component to display all reviews from a db and POST to create a new review from the Review component), but where should that happen? I can't tell if it has to happen in my express routes because it seems to me that all express is doing is rendering the static html page and then react-router is taking over after that with handling which components to display.
Any and all help is greatly appreciated.
For the GET request, you can load initial data in a separate function, than load that data in after the component has mounted using componentDidMount like so:
class Game extends React.Component {
constructor() {
this.state = { data: [] }
}
loadCommentsFromServer() {
$.ajax({
....
}
});
}
componentDidMount() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
}
}
You can do simply have another function for the POST.
I just wanna share my experience, hope it helps. I'm never doing a request on React Route although it can. So, I prefer to perform this action inside component itself on componentDidMount() method, in your case it will be on Game component.
My consideration is to make component reusable, especially if the the component is depends on the request. The benefit when you're implementing request inside the component is your component will automatically call for the request when it mount, wherever you're mounting the component on the route path.
Refers to my experience, you can also make a request on express as server side request, because there are particular condition that need to perform a request handling from server side. Such as handling Cross Origin Resource Sharing (CORS) issue when request to public API from client side, authentication request handling like using OAuth, and more.
If you're request is quite simple, I think request inside the component is sufficient.
Hope it helps. Thank you

TypeScript module omitted when only used as an alias

I have an import statement of a NPM module like this:
import * as ReactRouter from 'react-router'
Which transpiles using module: "commonjs" to:
var ReactRouter = require('react-router');
And I have access to ReactRouter.Router, etc. in my JSX. For example, this works:
render(){
return (
<ReactRouter.Router>
<ReactRouter.Route path="/" component={App}>
<ReactRouter.IndexRoute component={Index} />
<ReactRouter.Route path="detail/:id" component={Detail} />
{/* etc */}
</ReactRouter.Route>
</ReactRouter.Router>
)
}
However, I want to create aliases to Route, etc. so I don't have to refer ReactRouter.* everywhere:
import * as ReactRouter from 'react-router'
import Router = ReactRouter.Router
import Route = ReactRouter.Route
import IndexRoute = ReactRouter.IndexRoute
render(){
return (
<Router>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="detail/:id" component={Detail} />
{/* etc */}
</Route>
</Router>
)
}
But when I do this, the transpiled code becomes this:
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var IndexRoute = ReactRouter.IndexRoute;
Notice the ReactRouter module itself is nowhere, and at runtime it breaks because ReactRouter is undefined. However, if I stick at least one arbitrary reference to ReactRouter it shows up:
// TS
import * as ReactRouter
import Router = ReactRouter.Router
ReactRouter // reference to force ReactRouter module to be compiled
// Transpiles to:
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
ReactRouter;
And then it works at runtime.
So in other words, it seems that an import alias does not count as a reference, even though it really is. Is this a TSC bug? Is there a workaround other than creating an extra reference to the module so that TSC doesn't omit it? Is there a better way to import these individual symbols from the react-router module, like import {Router, Route, IndexRoute} from 'react-router' can be done with Babel?
This is a compiler bug. It was fixed a little while ago and you can either npm install typescript#next or use TypeScript 1.7 once it becomes available.
Referencing ReactRouter in an expression is the best workaround.