使用通行证和reactjs进行身份验证

时间:2020-03-23 18:08:17

标签: javascript node.js reactjs

我想为我的申请创建认证系统。 贝娄是我从节点js发布请求的代码:

app.post('/register', checkNotAuthenticated, async (req, res) => {
  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)

    users.push({
      id: Date.now().toString(),  //i don't use database, just an array
      name: req.body.name,
      password: hashedPassword
    })
    console.log(users)
    res.redirect('/login')
  } catch {
    res.redirect('/register')
  }
})

以下是我的反应邮政编码:

const Register = () => {
    const [name, setName] = useState('')
    const [password, setPassword] = useState('')
    const nameChange = (e) => {
        const val = e.target.value;
        setName(val)
    }
    const passwordChange = (e) => {
        const val = e.target.value;
        setPassword(val)
    }
    const register = (e) => {
        e.preventDefault()
        console.log('register: ' + name + password)
        const data = {
            name: name,
            password: password
        };
        const requestOptions = {
            method: 'post',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },

            body: JSON.stringify( {name:name,password: password})
        };
        fetch('http://localhost:4000/register', requestOptions)
            .then((response) => response.json())
            .then((messages) => {console.log(messages);});
    }
    return (
        < div>
            <h1>Register</h1>
            <form onSubmit={register}>
                <input value={name} onChange={nameChange} type="text" placeholder='name' name='name'/>
                <input value={password} onChange={passwordChange} type="text" placeholder='password' name='password'/>
                <input type="submit" value='Register'/>
            </form>
        </div>
    )
        ;
};

export default Register;

两个组件均有效。我可以在节点js中显示数据。

以下是我在节点js中的登录代码:

app.post('/login', checkNotAuthenticated, passport.authenticate('local', {    
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: true
}))

和我登录的react组件几乎就像上面的post请求。如何从登录组件获取发送数据到节点JS的登录。我不知道如何连接它们。那么,如何从reactjs的post组件中获取数据,并使用该数据进行授权? 我知道我应该使用以下代码:

 app.post('/login', checkNotAuthenticated, passport.authenticate('local', {    
      successRedirect: '/',
      failureRedirect: '/login',
      failureFlash: true
    }))

但是我不知道该如何连接我的UI。谁知道如何进行身份验证?

0 个答案:

没有答案