首页 > 解决方案 > 如何在 Reactjs 中加密请求负载

问题描述

我正在使用 react js,使用额外的 cryptojs 作为加密,我在请求数据有效负载时尝试加密..

我已经完成了一种方法,例如将 passReqToCallback 添加到我的护照,但它仍然没有在控制台请求中得到结果

我已将结果作为对象 {data: result} 添加到加密中,但它作为有效负载请求仍然不可读,而是作为数据形式读取

但结果总是 400 个错误请求。最好的方法是什么?

我的 reactjs 代码

const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const postData = {data: encrypt(values)}
                setSubmit(true);
                // eslint-disable-next-line no-undef
                axios.post(`${API}/signin`, postData)
                .then(response => {
                    return console.log('response', response.data);

                    const data = decrypt(response.data);
                    setSubmit(false)
                    if ( _.isString(data) ) {
                        contentNotification({
                            type     : 'error',
                            title    : 'Error',
                            placement: 'topLeft',
                            content  : data
                        })
                    } else {
                        contentNotification({
                            type     : 'success',
                            title    : 'Success',
                            placement: 'topLeft',
                            content  : formatMessage({id: 'LOGIN.SUCCESS'})
                        });

                        cookies.set('ckmsbp', response.data);
                        router.push('/');
                    }
                })
                .catch(err => {
                    contentNotification({
                        type     : 'error',
                        title    : 'Error',
                        placement: 'topLeft',
                        content  : formatMessage({id: 'LOGIN.ERROR_VALIDATE'})
                    })
                    setSubmit(false)
                    console.error(err);
                });
            }
        });
    };

这是我的路线:

app.post(`${api_path}/signin`, 
            validateBody(schemas.loginAccSchema),
            requireSignIn,
        (req, res, next) => {

            const { user }    = req
            const { decrypt } = req.query
                  params      = { user, decrypt };

            const c_account   = new ControllerAccount(params);
            c_account._postSignin(doc => res.status(200).json(doc))
    });

最后我的护照

passport.use(new LocalStrategy({
    usernameField    : 'email',
passReqToCallback : true
  }, async (req, email, password, done) => {
    // return console.log('req', req);

but do nothing here.. i can't console my request

    try{
...
}
catch{...} 

提前致谢

标签: node.jsreactjsencryptionaxioscryptojs

解决方案


在我发现自己并最终找到我想要的东西之后。

在有效载荷上加密数据的最佳方法是将其加密为一个对象,然后当控制器上接收到数据时,它会再次被解密

那么当护照中的本地策略只需要电子邮件和密码时最重要的方式..所以在 req.body 中再次操纵

在反应js

const result = {data : encrypt(values)}
axios.post(`${API}/signin`, result) // I simplify the coding

之后在控制器nodejs中

app.post(`${api_path}/signin`, 
            validateBody(schemas.loginEncryptAccSchema),
            requireSignIn, //focus in this function
        (req, res, next) => {
            const { user }    = req;
            const { decrypt } = req.query
                  params      = { user, decrypt };
            return console.log('params', params); // i stopped

            const c_account   = new ControllerAccount(params);
            c_account._postSignin(doc => res.status(200).json(doc))
    });

requireSignin 函数

const requireSignIn       = (req, res, next) => {
        const data     = req.body.data;
        const bytes    = CryptoJS.AES.decrypt(data, `${KEY_CHAIN}`); //i decrypt
              req.body = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); //then i assign into req.body again
        passport.authenticate('local', { session : false })(req, res, next);
    }

终于完结了 xD


推荐阅读