任何人都可以提供帮助,请我仍在学习React + Axios并因请求400失败而卡住。我确实用'http://localhost:3000/users/login'更改了axios发布'users / login',但无法解决。我在带有身份验证的axios帖子中又传递了1个参数。
谢谢,我需要专家帮助我。
Login.js
import { login } from './UserFunctions'
class Login extends Component {
constructor() {
super()
this.state = {
email: '',
password: '',
errors: {}
}
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
onSubmit(e) {
e.preventDefault()
const user = {
email: this.state.email,
password: this.state.password
}
login(user)
.then(res => {
if (res) {
this.props.history.push(`/profile`)
}
})
.catch(err => {
console.log(err)
})
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6 mt-5 mx-auto">
<form noValidate onSubmit={this.onSubmit}>
<h1 className="h3 mb-3 font-weight-normal">Please sign in</h1>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input
type="email"
className="form-control"
name="email"
placeholder="Enter email"
value={this.state.email}
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
name="password"
placeholder="Password"
value={this.state.password}
onChange={this.onChange}
/>
</div>
<button
type="submit"
className="btn btn-lg btn-primary btn-block"
>
Sign in
</button>
</form>
</div>
</div>
</div>
)
}
}
export default Login
UserFunctions.js
import axios from 'axios'
export const register = newUser => {
return axios
.post('users/register', {
first_name: newUser.first_name,
last_name: newUser.last_name,
email: newUser.email,
password: newUser.password
})
.then(response => {
console.log('Registered')
})
.catch(err => {
console.log(err)
})
}
export const login = user => {
return axios
.post('users/login', {
email: user.email,
password: user.password
})
.then(response => {
console.log(response.data.token);
localStorage.setItem('usertoken', response.data)
return response.data
})
.catch(err => {
console.log(err)
})
}
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.1",
"jwt-decode": "^2.2.0",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-router-dom": "^5.0.0",
"react-scripts": "1.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:5000/"
}
Users.js
const express = require('express')
const users = express.Router()
const cors = require('cors')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const User = require('../models/User')
users.use(cors())
process.env.SECRET_KEY = 'secret'
users.post('/register', (req, res) => {
const today = new Date()
const userData = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
created: today
}
User.findOne({
where: {
email: req.body.email
}
})
//TODO bcrypt
.then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({ status: user.email + 'Bcrypt Registered!' })
})
.catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({ error: 'User already exists' })
}
})
.catch(err => {
res.send('error: ' + err)
})
})
users.post('/login', (req, res) => {
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (user) {
bcrypt.compare(req.body.password, hash, function(err, res) {
if(res) {
console.log('User Logged Successfully')
let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
expiresIn: 1440
})
res.send(token)
} else {
console.log('Username / Password Wrong')
}
});
} else {
res.status(400).json({ error: 'User does not exist' })
}
})
.catch(err => {
res.status(400).json({ error: err })
})
})
users.get('/profile', (req, res) => {
var decoded = jwt.verify(req.headers['authorization'], process.env.SECRET_KEY)
User.findOne({
where: {
id: decoded.id
}
})
.then(user => {
if (user) {
res.json(user)
} else {
res.send('User does not exist')
}
})
.catch(err => {
res.send('error: ' + err)
})
})
module.exports = users