[使用React和Node从API调用我的函数

问题描述 投票:0回答:1

我需要从我的API调用我的connexion()(api / connexion)到前端(使用react),这是一个身份验证函数,它应该生成一个令牌,并且我需要在前端获得这个令牌(render())用它来列出我的联系人,例如

[我所做的是使用邮递员代码中包含的令牌获得联系,我不必这样做,当connexion()很好时应使用令牌。

connexion()验证我是否插入了正确的电子邮件和密码,并生成令牌。

        super(props);
        this.state = {
            // name: "",
          cnx_mail: '',
          cnx_pwd: '',
          joinByEmail: '',
          items: [],
          token : '',
          redirectToReferrer:false,
          errors: {},

          formErrors: {cnx_mail: '', cnx_pwd: ''},
          emailValid: false,
          passwordValid: false,
          formValid: false
        }
         this.handleUserInput = this.handleUserInput.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
        event.preventDefault();
        let token = localStorage.getItem('tok');
// const token = user.data.result;
        axios.post(`${API}/api/connexion`)
        .then(res => {
            console.log(token);    
            console.log(res);

        this.setState({
            items: res.data,  /*set response data in items array*/
            // isLoaded : true,
            // redirectToReferrer: false
        })})
        // console.log(this.items)
      }

                                <form className="demoForm" onSubmit={this.handleSubmit} noValidate  encType="application/x-www-form-urlencoded">
                                    <div className="alreadysubscribed-input">
                                        <div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_mail)}`}>
                                            <input type="email" required className="form-control fatb-input input-form" name="cnx_mail"
                                                value={this.state.cnx_mail}
                                                id="cnx_mail"
                                                onChange={this.handleUserInput} error={errors.cnx_mail} />
                                                <label className="fatb-label" htmlFor="cnx_mail">Email</label>
                                                <div className="fatb-bar"></div>                                  
                                        </div>

                                        <div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_pwd)}`}>
                                            <input type="password" required className="form-control fatb-input input-form" name="cnx_pwd"
                                                value={this.state.cnx_pwd}
                                                id="cnx_pwd"
                                                onChange={this.handleUserInput} error={errors.cnx_pwd} />
                                                <label className="fatb-label" htmlFor="cnx_pwd">Mot de passe</label>
                                                <div className="fatb-bar"></div>
                                        </div>
                                    </div>
                                    <FormErrors formErrors={this.state.formErrors} />

                                    <div className="btn-cnx">
                                        {/* <span className="mas">Se connecter</span> */}
                                        <button className="fatb-btn bubbly-button btn-anim3 w100p" type="submit"  name="cnx_btn" disabled={!this.state.formValid}>se connecter</button>
                                    </div>
                                </form>

这是后端的connexion():

/**
 * POST /api/connexion 
 */
exports.connnexion = (req, res) => {
    try{
        var email = req.body.email;
        var password = req.body.password;
        //get email and password
        if( ( (typeof email !== 'undefined') || (email === '') ) || 
        ( (typeof password !== 'undefined') || ( password === '') ) ){
            //check email if Exist in DB
            Account.find({email : email},function(err, account){
                if (err){
                    resultats = {
                        "success": false,
                        "message": "Error : "+err,
                        "result": ''
                    }
                    res.json(resultats);
                }
                else{
                    if((account[0].google.id)===undefined && (account[0].facebook.id)===undefined){//dont have google & facebook account
                        console.log('connexion classique');
                        if(account.length){
                            //if exist,
                            //get password of this account
                            if(bcrypt.compareSync(password,account[0].password)){//if password ok
                                //create new token
                                try{
                                    jwt.sign({
                                        account
                                    },
                                    'secretKey',
                                    (err,token) => {
                                        if(err){
                                            resultats = {
                                                "success": false,
                                                "message": 'Error : '+ err,
                                                "result": ''
                                            }
                                            res.json(resultats);
                                        }
                                        resultats = {
                                            "success": true,
                                            "message": "SUCCESS",
                                            "result": token
                                        }
                                        res.json(resultats); 
                                    }); 
                                }catch(e){
                                    resultats = {
                                        "success": false,
                                        "message": 'Error : '+ e,
                                        "result": ''
                                    }
                                    res.json(resultats);
                                }
                            }
                            else{
                                resultats = {
                                    "success": false,
                                    "message": "Error, check email/password",
                                    "result": ''
                                }
                                res.json(resultats);
                            }

                        }
                        else{
                            resultats = {
                                "success": false,
                                "message": 'Error : check email/password',
                                "result": ''
                            }
                            res.json(resultats);
                        }
                    }
                    else{
                        console.log('impossible de se connecter(google ou facebook)');
                        resultats = {
                            "success": false,
                            "message": "Error, check email/password",
                            "result": ''
                        }
                        res.json(resultats);
                    }

                }
            });
        }
        else{
            resultats = {
                "success": false,
                "message": 'Error : check email/password',
                "result": ''
            }
            res.json(resultats); 
        }
    }catch(e){
        resultats = {
            "success": false,
            "message": 'Error : '+ e,
            "result": ''
        }
        res.json(resultats); 
    }
}

使用此代码,我得到了代币(使用console.log(token))以及使用api / connexion生成的所有这些数据:

config: {url: "http://localhost:3001/api/connexion", method: "post", headers: {…}, transformRequest: Array(1), transformResponse: Array(1), …}
data: {success: false, message: "Error : check email/password", result: ""}
headers: {content-type: "application/json; charset=utf-8", content-length: "70"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
__proto__: Object

但是如果您在'数据'上看到它,我们就会得到:

message: "Error : check email/password"
result: ""
success: false

而不是结果:the_token和消息:成功,成功:真

PS:在邮递员中,它运作得很好:

{
    "success": true,
    "message": "SUCCESS",
    "result": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjpbeyJkYXRlQ3JlYXRpb24iOiIyMDE5LTEwLTA5VDIxOjU0OjE4LjQ5MVoiLCJyZXNldHBhc3N3b3JkdG9rZW4iOm51bGwsInJlc2V0cGFzc3dvcmRleHBpcmVzIjpudWxsLCJyb2xlIjoiYWRtaW4iLCJlbmFibGUiOnRydWUsIl9pZCI6IjVkOWU2NzdlMjY4Mjk3MWMxZmMzNzExZCIsImVtYWlsIjoibWlrYS5hY2hlbWxhbEBnbWFpbC5jb20iLCJwYXNzd29yZCI6IiQyYiQxMCRCZzRuT3JOTXpjLmIvSkJOS05pUlAuQmlNZC8uaDRDSEtpeTBudlYvdWltMGQzVndIbDlpcSIsInRpY2tldHMiOltdLCJnYWlucyI6W10sIl9fdiI6MH1dLCJpYXQiOjE1NzE4NTc0ODV9.cGfWeWxaz2fKs8LIVEGzQvQXmRiE63GDioVN2IMerfg"
}

谢谢

node.js reactjs api express webpack
1个回答
0
投票

我找到了这个解决方案:

   handleSubmit = (event) => {
        event.preventDefault();
        fetch(`${API}/api/connexion`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',   
              },
            body: JSON.stringify ({
                email: this.state.cnx_mail,
                password: this.state.cnx_pwd,
              })
        })
        .then(res => res.json())
        .then(json => {
            console.log(json);
            localStorage.setItem('token', json.result);
        }); 
      }

现在我必须获取“令牌”才能在所有组件上使用它”>

© www.soinside.com 2019 - 2024. All rights reserved.