React Question App Overview

0

Category :

Developing Question Application with React

With your backend API up and running, you are finally ready to start developing your React application.

With the "create-react-app" tool, you can scaffold a new React application with just one command. As such, to create your React app, open a new terminal and go to the same directory where you created the qa-api Node.js app. From there, issue the following command:

# this command was introduced on npm@5.2.0
npx create-react-app qa-react

This will make NPM download and run create-react-app in a single command, passing to it qa-react as the desired directory for your new application.

# move into the new directory
cd qa-react

# start your React app
npm start

The last command issued above will start a development server that listens on port 3000 and will open the new app in your default web browser.

After seeing your app, you can stop the server by hitting
Ctrl + c 

Configuring the React Router in Your App

React Router is a very complete solution and, in your first React app, you will touch only the tip of the iceberg. If you do want to learn more about React Router, please, head to the official documentation.

Configuring Bootstrap in Your React App

To make your React app more appealing from the User Interface (UI) point of view, you are going to configure Bootstrap on it.

Creating a Navigation Bar in Your React App

create a component called NavBar (which stands for Navigation Bar), and you will add it to your React app.

Creating a Class Component with React

create a stateful component (a class component) to fetch questions from your backend and to show it to your users. To fetch these questions, you will need the help of another library, Axios. In a few words, Axios is a promise-based HTTP client for the browser and for Node.js. Note: This component is touching a topic that was not addressed in this article, the Lifecycle of React Components. In this case, you are just using one of the extension points provided by React, the componentDidMount method.

Routing Users with React Router

import React, { Component } from 'react';
import {Route} from 'react-router-dom';
import NavBar from './NavBar/NavBar';
import Question from './Question/Question';
import Questions from './Questions/Questions';

class App extends Component {
  render() {
    return (
      
); } } export default App;

In the new version of your App component, you are using two Route elements (provide by react-router-dom) to tell React when you want the Questions component rendered and when you want the Question component rendered.
More specifically, you are telling React that if your users navigate to / (exact path='/') you want them to see Questions and, if they navigate to /question/:questionId, you want them to see the details of a specific question.

Configuring an Auth0 Account

If you do not have one, now is a good time to sign up for a free Auth0 account. With your free account, you will have access to the following features:

Create Application
Set Allowed Callback URLs field

Securing your Backend API with Auth0

To secure your Node.js API with Auth0, you will have to install and configure only two libraries:
  • express-jwt: A middleware that validates a JSON Web Token (JWT) and set the req.user with its attributes.
  • jwks-rsa: A library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.

both of them declare that they want to use checkJwt, which makes them unavailable to unauthenticated users. Second, both add a new property called author on questions and answers. These new properties receive the name (req.user.name) of the users issuing requests.

Securing your React App with Auth0

install only one library: auth0-js. This is the official library provided by Auth0 to secure SPAs like yours.

refactor your NavBar component to allow users to authenticate. So, open the NavBar.js file and replace its code

After refactoring the NavBar component, you will have to create a component to handle the callback. This componet will be responsible for 2 things:
First, it calls the handleAuthentication method to fetch the user information sent by Auth0.
Second, it redirects your users to the home page (history.replace('/')) after it finishes the handleAuthentication process. In the meantime, this component shows the following message: "Loading profile".

Adding Features to Authenticated Users

First, you will enable authenticated users to create new questions. Then, you will refactor the Question (singular) component to show a form so authenticated users can answer these questions.

Keeping Users Signed In after a Refresh

if you refresh your browser, you will notice that you will be signed out. Because you are saving you tokens in memory (as you should do) and because the memory is wiped out when you hit refresh.

Luckily, solving this problem is easy. You will have to take advantage of the Silent Authentication provided by Auth0. That is, whenever your application is loaded, it will send a silent request to Auth0 to check if the current user (actually the browser) has a valid session.

You will have to change a few configurations in your Auth0 account.
Add your url http://localhost:3000 to Allowed Web Origins, as your app is going to issue an AJAX request to Auth0.
Add your url http://localhost:3000 to Allowed Logout URLs, To enable users to end their session at Auth0, you will have to call the logout endpoint. Similarly to the authorization endpoint, the log out endpoint only redirects users to whitelisted URLs after the process.

Now update the src/Auth.js file to implement silent login when component has loaded

There are a lot of links on the original article that should be used to investigate further and delve deeper into the technologies used.

my thanks to this great blog post:
https://auth0.com/blog/react-tutorial-building-and-securing-your-first-app/

Developing a Backend API with Node.js and Express

0

Category :

In the following sections, you will build a simple Q&A (Question & Answer) app that will allow users to interact with each other asking and answering questions. To make the whole process more realistic, you will use Node.js and Express to create a rough backend API.

Developing a Backend API with Node.js and Express

build a backend API to support your Q&A app. In this section, you will use Express alongside with Node.js to create this API. With this library, as you will see here, you can quickly build apps to run on servers
# use NPM to start the project
npm init -y

this will create a file called package.json inside your directory. This file will hold the details (like the dependencies) of your backend API.

npm i body-parser cors express helmet morgan
This command will install five dependencies in your project:
  1. body-parser:
    This is a library that you will use to convert the body of incoming requests into JSON objects.
  2. cors:
    This is a library that you will use to configure Express to add headers stating that your API accepts requests coming from other origins. This is also known as Cross-Origin Resource Sharing (CORS).
  3. express:
    This is Express itself.
  4. helmet:
    This is a library that helps to secure Express apps with various HTTP headers.
  5. morgan:
    This is a library that adds some logging capabilities to your Express app.

Also, you will see a new file called package-lock.json. NPM uses this file to make sure that anyone else using your project (or even yourself in other environments) will always get versions compatible with those that you are installing now.

Then, the last thing you will need to do is to develop the backend source code. So, create a directory called src inside your qa-api directory and create a file called index.js

//import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');

// define the Express app
const app = express();

// the database
const questions = [];

// enhance your app security with Helmet
app.use(helmet());

// use bodyParser to parse application/json content-type
app.use(bodyParser.json());

// enable all CORS requests
app.use(cors());

// log HTTP requests
app.use(morgan('combined'));

// retrieve all questions
app.get('/', (req, res) => {
  const qs = questions.map(q => ({
    id: q.id,
    title: q.title,
    description: q.description,
    answers: q.answers.length,
  }));
  res.send(qs);
});

// get a specific question
app.get('/:id', (req, res) => {
  const question = questions.filter(q => (q.id === parseInt(req.params.id)));
  if (question.length > 1) return res.status(500).send();
  if (question.length === 0) return res.status(404).send();
  res.send(question[0]);
});

// insert a new question
app.post('/', (req, res) => {
  const {title, description} = req.body;
  const newQuestion = {
    id: questions.length + 1,
    title,
    description,
    answers: [],
  };
  questions.push(newQuestion);
  res.status(200).send();
});

// insert a new answer to a question
app.post('/answer/:id', (req, res) => {
  const {answer} = req.body;

  const question = questions.filter(q => (q.id === parseInt(req.params.id)));
  if (question.length > 1) return res.status(500).send();
  if (question.length === 0) return res.status(404).send();

  question[0].answers.push({
    answer,
  });

  res.status(200).send();
});

// start the server
app.listen(8081, () => {
  console.log('listening on port 8081');
});
With this file in place, you are good to go. To run your app, just issue the following command:
# from the qa-app directory
node src

Test if everything is really working, open a new terminal and issue the following commands:

# issue an HTTP GET request
curl localhost:8081

# issue a POST request
curl -X POST -H 'Content-Type: application/json' -d '{
  "title": "How do I make a sandwich?",
  "description": "I am trying very hard, but I do not know how to make a delicious sandwich. Can someone help me?"
}' localhost:8081

curl -X POST -H 'Content-Type: application/json' -d '{
  "title": "What is React?",
  "description": "I have been hearing a lot about React. What is it?"
}' localhost:8081

# re-issue the GET request
curl localhost:8081
With your backend API up and running, you are finally ready to start developing your React application.

my thanks to this great blog post:
https://auth0.com/blog/react-tutorial-building-and-securing-your-first-app/

React Basics Intro

0

Category :

React and the JSX Syntax

React uses a funny syntax called JSX. JSX, which stands for JavaScript XML, is a syntax extension to JavaScript that enables developers to use XML (and, as such, HTML) to describe the structure of the user interface.

function showRecipe(recipe) {
  if (!recipe) {
    return 

Recipe not found!

; } return (

{recipe.title}

{recipe.description}

); }

In this case, the showRecipe function is using the JSX syntax to show the details of a recipe (i.e., if the recipe is available) or a message saying that the recipe was not found.

React Components

Components in React are the most important pieces of code. Everything you can interact with in a React application is (or is part of) a component. For example, when you load a React application, the whole thing will be handled by a root component that is usually called App.

The biggest advantage of using components to define your application is that this approach lets you encapsulate different parts of your user interface into independent, reusable pieces. Having each part on its own component facilitates reasoning, testing, and reusing each piece easily.

Defining Components in React

there are two types of React components

functional components
are simply "dumb" components that do not hold any internal state (making them great to handle presentation)
function UserProfile(props) {
  return (
    

{props.userProfile.name}

); }

class components
Are more complex components that can hold internal state. For example, if you are creating a component that will only show the profile of the user that is authenticated, you can create a functional component as follows:

However, if you are going to create a component to handle things that need to hold some state and perform more complex tasks, like a subscription form, you will need a class component. To create a class component in React, you would proceed as follows:
class SubscriptionForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      acceptedTerms: false,
      email: '',
    };
  }

  updateCheckbox(checked) {
    this.setState({
      acceptedTerms: checked,
    });
  }

  updateEmail(value) {
    this.setState({
      email: value,
    });
  }

  submit() {
    // ... use email and acceptedTerms in an ajax request or similar ...
  }

  render() {
    return (
      
{this.updateEmail(event.target.value)}} value={this.state.email} /> {this.updateCheckbox(event.target.checked)}} />
) } }

this component is defining three input elements (actually, two input tags and one button

this component is defining an internal state (this.state) with two fields: acceptedTerms and email

my thanks to this great blog post:
https://auth0.com/blog/react-tutorial-building-and-securing-your-first-app/