Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

栏目: IT技术 · 发布时间: 5年前

内容简介:Previous article:For the Frontend, we will use ReCaptcha protected form;For backend, we will define CORS, which will be receiving requests only from the Frontend.
Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

Setup ReCaptcha and define CORS

Previous article: Optimize App and Setup Deployment Workflow .

For the Frontend, we will use ReCaptcha protected form;

For backend, we will define CORS, which will be receiving requests only from the Frontend.

Setup ReCaptcha protected frontend

Step one:We will get Recaptcha key from Google

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

Google Recaptcha setting domain page

Step two:Add our whitelist domain, then choose localhost and Netlify, then grab Recaptcha key, and finally, set up on Netlify first

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

Google Recaptcha api key

Step three:Setting up on Netlify. Go to Netlify dashboard and setup Recaptcha Key as an environment variable

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

Netlify deploy setting page

Step four:Now come back to local and install React Captcha package

npm install react-recaptcha

Step five: Next step is to import Recaptcha

import Recaptcha from "react-recaptcha";

Step six:Add validation rule name Recaptcha as required

const LoginSchema = Yup.object().shape({
   username: Yup.string()
                .min(2, "username is Too Short!")
                .max(50, "username is Too Long!")
                .required("Username is Required"),
            recaptcha: Yup.string().required(),
            password: Yup.string().required("Password is required")
   });

Step seven:We will create a function for initializing Recaptcha

initilizeRecaptcha = async => {
    const script = document.createElement("script");
    script.src = "https://www.google.com/recaptcha/api.js";
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
  };
  componentDidMount() {
    this.initilizeRecaptcha();
}

Last step:Add <Recaptcha> component and a validation message

<div className="form-group">
          <label>Recaptcha Validation</label>
          <Recaptcha
            sitekey={process.env.REACT_APP_RECAPCHA_KEY}
            render="explicit"
            theme="light"
            verifyCallback={response => {
              setFieldValue("recaptcha", response);
            }}
            onloadCallback={() => {
              console.log("done loading!");
            }}
          />
     {errors.recaptcha && touched.recaptcha && <p>{errors.recaptcha}</p>}
 </div>

Your final result should look like the image below

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

add ReCaptcha to login page

One more step:We’ll be adding register and forgot password form

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

add ReCaptcha to register page

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

add ReCaptcha to login page

You will be able to fill all input, but can’t submit without resolving the Recaptcha

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

ReCaptcha require validation

The last thing is to push to GitHub which will also auto-deploy to Netlify

Setup CORS protected backend

Now we want to add whitelist IP or domain name to CORS option, open index.js on backend side then update CORS as seen in the image below;

var allowedOrigins = ['http://localhost:3000',
                      'https://basicpos.netlify.com/'];
app.use(cors({
  origin: function(origin, callback){
    // allow requests with no origin 
    // (like mobile apps or curl requests)
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
      var msg = 'The CORS policy for this site does not ' +
                'allow access from the specified Origin.';
      return res.json({status:'error',msg});
    }
    return callback(null, true);
  }
}));

If an error occurs, try changing to another domain

Create simple POS with React, Node and MongoDB #5: Setup ReCaptcha and define CORS

CORS error result

Now push the updated code to Github. Finally, we can now protect our backend from unknown request

Conclusion

In this chapter, we have learned how to make our apps safe on the internet by setting up Recaptcha on React and CORS on Express. next chapter we will add redux that make our app are solid foundation one last thing your will find code for this chapter on this backend branch and frontend branch

Previous lessons:


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Orange'S:一个操作系统的实现

Orange'S:一个操作系统的实现

于渊 / 电子工业出版社 / 2009-6 / 69.00元

《Orange S:一个操作系统的实现》从只有二十行的引导扇区代码出发,一步一步地向读者呈现一个操作系统框架的完成过程。书中不仅关注代码本身,同时关注完成这些代码的思路和过程。本书不同于其他的理论型书籍,而是提供给读者一个动手实践的路线图。读者可以根据路线图逐步完成各部分的功能,从而避免了一开始就面对整个操作系统数万行代码时的迷茫和挫败感。书中讲解了大量在开发操作系统中需注意的细节问题,这些细节不......一起来看看 《Orange'S:一个操作系统的实现》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具