React router 4 - Link to page outside react app - node.js

I'm building a node + react app that uses passport's facebook authentication. Getting this authentication to work involves hitting an express route '/auth/facebook'. Unfortunately as soon as the react app loads up react router 4 doesn't allow links to directly hit the express server and instead searches for a react route matching 'auth/facebook'. In short how do I link to a route within my application but outside of the react app when using react router 4?

React Router is only for client side routing. Use fetch API or a similar library for that.
I'll state one way of solving your problem (using fetch and without react router).
Remove the href from the <a> tag
Add an event listener for the click event, <a onClick={makeCall}>
Then in the makeCall function, you can call the backend using the fetch API(or axios or whatever),
makeCall() {
fetch('/auth/facebook', options)
.then((res) => {
// Something
})
.catch((err) => {
// handle error
});
}

Related

Route to React component from Express

I've got an express backend and want to send the user a react component when a specific route is requested from the server. How can I do this?
I've also got react-router setup on the frontend, but I'm unable to redirect to a react route when an express route is requested...
use axios.
let result = await axios.get("url<localhost>/route<api route of express>");

React fullstack architecture: When adding a react front-end to a node/express application, what aspects does react's state generally handle?

I have a fully built node/express application that I want to add react to in order to practice that relationship in full stack applications. I've built apps in react before, and in node, but never together and I am confused about how react fits into the MVC architecture.
In a react-node full stack application does react state then handle all of the data I was previously passing into my ejs views?
I have been looking through tutorials on full stack applications with node and react, but they only seem to go into issues like how does react fetch data from the back end, or how to set up the configuration,
but I get that part, I just don't understand what react does in a full stack application, what part of the model-controller-view architecture of a node/express backend app does react take over? How are the responsibilities split between the backend and front end?
So for example, I'm working with a reddit-clone type app so when you click on a post title to see the post my controller queries the database for that post and then passes it to the view as {post}:
show(req, res, next){
postQueries.getPost(req.params.id, (error, post) => {
if(error || post == null){
res.redirect(404, "/");
} else {
res.render("posts/show", {post});
}
});
},
So when I add a front-end with react, would that {post} object then be something handled by react? So react would fetch that data and use it in a post component to create what is currently my view show.ejs file?
So when I add a front-end with react, would that {post} object then be something handled by react? So react would fetch that data and use it in a post component to create what is currently my view show.ejs file?
Yes. The show.ejs would be a React view or a page that contains a component to handle how to show it.
To simplify:
React -- is a virtual DOM, so it'll swap views/containers/components in and out based upon events (like clicking a button), which in turn, will: retrieve, display, manipulate and/or send data to the API. In development, it is completely separate from your back-end. All the routing will be handled by a front-end router package. In production, all of the front-end src code is compiled into a dist or build folder that contains your assets (images, fonts, css) and most importantly bundle.js file(s) that are then served by express.
Express + some database -- will act as your API where it'll CRUD data based upon the front-end request(s). If your app is a MPA (multiple page application), then a common practice is to delineate your back-end routes from your front-end routes with a /api/ prefix. In production, if express doesn't recognize the route (it's not a /api/ request), then it'll fall back into the front-end bundle.js file where it'll be handled by the front-end router.
See a working example here: https://github.com/mattcarlotta/fullstack-mern-kit (client is the frontend, everything else is the backend)
Or
See a working codesandbox (where I'm making a GET request to an API that returns json):
For your example above, your show controller will just be sending JSON (or a string message) back to the frontend (redirects will happen on the frontend via a router -- like react-router-dom):
show(req, res, next){
postQueries.getPost(req.params.id, (error, post) => {
if(error || post == null){
// res.status(404).send("Unable to locate posts.");
res.status(404).json({ err: Unable to locate posts });
} else {
res.status(200).json({ post });
}
});
},
You can even simplify the above using async/await:
const show = async (req, res, done) => {
try {
const post = await postQueries.getPost(req.params.id);
res.status(200).json({ post });
} catch(err) {
// res.status(404).send("Unable to locate posts.");
res.status(404).json({ err: Unable to locate posts });
}
};
And then the React front-end handles the response.

Node.js / Express.js + Angular router - server overwriting client view with response object when using direct link

I am building a node.js app with express, I am hosting an Angular SPA in the public folder.
The app runs and the hosting works fine when I use the angular router for navigation around the website, but when I directly try to access the link, for example: http://192.168.1.4:3000/posts, the entire body of the website is just the JSON response object, without the app
this is the Node.js code handling the get request
postRouter.route('/')
.options(cors.corsWithOptions, (req, res) => {
res.sendStatus(200);
})
.get(cors.cors, (req, res, next) => {
posts.find({})
.then((post) => {
res.status(200);
res.setHeader('Content-Type', 'application/json')
res.send(post);
}, (err) => next(err))
.catch((err) => next(err));
})
this is my angular service sending out the get request
getPosts(): Observable<Post[]> {
return this.http.get(baseURL + 'posts')
.catch(error => { return this.processHttpService.handleError(error); });
}
Post Component .ts file
ngOnInit() {
this.postService.getPosts()
.subscribe(posts => { this.posts = posts, console.log(this.posts); },
errmess => this.errMess = <any>errmess);
}
Again, when i use my Angular 5 client app hosted in the public folder, built with ng build --prod, the JSON object is retrieved from the mongodb database and is displayed correctly on my website, along with the rest of the app, the header, the body, and the footer.
it might also be worth noting that the console.log on the ngOnInit() is not displayed on the browser when using the direct link.
Any advice/fix is greatly appreciated
You have a clash of routes between angular and your express application. Angular is served up on one route (I'm guessing the / route) and then it sort of "hijacks" the users navigation. It does this by not actually changing web pages, instead it just changes the URL in the navigation bar, but never actually makes a web request to get to that resource.
You've then got endpoints on a web server listening on those endpoints. This means the moment you visit the /posts page, you're not asking angular to do anything. In fact, angular isn't even loaded because that only gets loaded on the / route. Instead you're going straight to your API.
There are ways around this, to start with many people put their API fairly separately, either on a subdomain or mounted on /api (such as /api/posts). Then your angular app can be served up on the / route. There are other techniques you can use to then allow a user to go to /posts and still get your angular app loaded.
You can use a few approaches for this such as the hash location strategy, or you can serve up your angular application from any route on the application (* in express) and load the angular app which will then take over. This second approach is most comment, it usually results in hosting your api on a sub domain and then serving your angular app on the * route of the normal domain name. For example: api.myapp.com will serve only JSON responses, but any route on myapp.com will serve the angular app, such as myapp.com/posts.

How to add facebook authentication to my react app?

I'm using express as backend. I implemented facebook authentication at the backend.
router.get('/login/facebook',
passport.authenticate('facebook',{scope:['email']}));
router.get('/login/facebook/callback',
passport.authenticate('facebook',{
successRedirect : '/home',
failureRedirect:'/'
})
);
Now I want to call this through my react app, so that when the user lands up at home page, first he should be authenticated by facebook then only he can see homepage. How can I do this ?
I tried using react-router, but I can't understand how to call backend using react-router.
I also fetched /login/facebook using fetch command :
componentDidMount(){
fetch("127.0.0.1:3001/login/facebook");
But it gave me CORS error.
My react app is at 127.0.0.1:3000 and express server at 127.0.0.1:3001.
If this issue is only in dev mode, then Daniel's answer is correct.
In any case, I recommend to avoid calling the :3001 api directly from the :3000 app. Here's what I would do.
I will edit the fetch call as follows,
componentDidMount(){
fetch("/login/facebook");
}
This call will be received by the backend which serves the react application.
Now there are three cases,
Case 1: Your file serving app will have a proxy method which can forward requests to an API. For example read it here
Case 2 This is my Recommended approach. I would simply write the authentication logic in the :3000 server and only use the :3001 API for handling business logic of the app.
Case 3: If you have a backend app (:3000), say written using expressJs, you can forward the request to the :3001 API. Here is a sample code for that,
client.send({
method: req.method,
path: req.url,
data: req.body,
params: req.params
}).then( (response) => {
// Something
}).catch( (err) => {
// Handle error
});
Here the client is a module which uses the request module to make HTTP calls.
You can implement the above call as an express middleware to use it for all HTTP calls.
There are several options:
If you are using webpack dev server, you can set up a proxy to your api. See here
You can temporary disable cors validation during development. See here

React Routing vs Express Routing

Been watching alot of tutorials and i see that there is express routing as well as react routing.
Is the react routing for client and the node js routing for server (api?).
Wanting to know if someone could please clarify this as new to React, Node, Express.
Thanks
It is possible (and even recommended) to use both of them in combination.
TL;DR
react-router is used to navigate between multiples pages/views of your front-end app/website. Usually in a single page app (SPA), where pages/views are loaded dynamically.
express router is a way to return static content (index.html, image.png...) AND to handle API calls that are often related to database logic. Those routes are handled server-side.
Example
myapp.com/my-portfolio is a view and should be handled and rendered by react router
// this router render pages components dynamically based on the url
<Route path="/my-portfolio" component={Portfolio} />
<Route path="/page2" component={Page2} />
myapp.com/user/create or myapp.com/api/getMyJson is an api call that should be handled server-side by express router:
// app.js
// api call that return json data
// this is where I will usually return database content
app.get('/api/getMyJson', (req, res) => {
res.send('{"my_var":"value"}');
});
// api call that return the content of folder app/public where
// the index.html and static resources are usually exposed
app.use(express.static('app/public'))
Single page application workflow
The front-end (client browser) request the back-end (your server) for the application static content (myLogo.png, index.html...) usually served by express router
While the first page is loaded and the user begin to interact with the app, the front-end continues to load other pages in the background (lazy loading)
When the user navigate to another page (with react-router), the page is already loaded and the user is taken there without any further server call nor page reloading
On another hand, express router need to handle API calls like myapp.com/user/userId/get/notifications to get data that is not "static" like json data.
I'll try explain the difference through an example. Say we have a single page application built with react at www.example.com
React Routing
We hit www.example.com and the index.html is loaded from the server. Note that it has all of your react pages in your bundle.js file. You now click the about button on the navbar, this sends you to www.example.com/about. This call does not hit the server, it is handled by your react router.
Express
Much like above we hit www.example.com and get the index. This time when we hit /about we get information from the server
Take a look at this blog post:https://medium.com/airbnb-engineering/isomorphic-javascript-the-future-of-web-apps-10882b7a2ebc

Resources