【发布时间】:2020-08-30 21:18:30
【问题描述】:
我正在尝试将用户数据(电子邮件和密码)传递到我的快速服务器以实现登录。我的代码有什么问题?我不断收到此错误:“请求失败,状态码为 400”。我已经向客户端 package.json 添加了这样的代理:“proxy”:“http://localhost:5000”。
React 组件中的代码:
import React, { Component } from "react"
import { connect } from 'react-redux'
import axios from 'axios'
class SigningPage extends Component {
state = {
signInEmail: '',
signInPassword: ''
}
handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}
handleSubmit = (e) => {
e.preventDefault();
const url = 'http://localhost:5000/login';
const user = {
email: this.state.signInEmail,
password: this.state.signInPassword
}
axios.post(url, user).then((res) => {
console.log(res)
}).catch((e) => {
console.log(e)
});
}
render() {
return <div>
<article>
<h1>Sign in</h1>
<form action="/login" method="post"onChange={this.handleInputChange} onSubmit={this.handleSubmit}>
<input
name="signInEmail"
type="email"
placeholder="email"
required>
</input>
<input
name="signInPassword"
type="password"
placeholder="password"
required>
</input>
<input type="submit" value="Submit form"}>
</form>
</article>
</div>
快速服务器中的代码
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const bcrypt = require('bcrypt')
const path = require('path')
const mongoose = require('mongoose')
const db = mongoose.connect("mongodb+srv://*****:**********@cluster0-ldqwn.mongodb.net/test?retryWrites=true&w=majority")
const UserSchema = mongoose.Schema({ email: String, password: String });
const MyModel = mongoose.model('Userss', UserSchema);
app.use(bodyParser.urlencoded({extended: true}))
app.post('/userSignUp', async (req, res)=>{
try {
const salt = await bcrypt.genSalt()
const hashedPassword = await bcrypt.hash(req.body.password, salt)
const userData = {email: req.body.email, password: hashedPassword}
MyModel.findOne(userData)
.then(exUs =>{
if(exUs){
console.log('exists')
} else {
new MyModel(userData).save(
(err, user) => {if (err)
{return console.error(err)} else {
console.log(user.email + " saved to bookstore collection.")}
}
)
}
}).catch(err => console.log(err))
} catch {
res.status(500).send()
}
})
app.post('/login', async (req, res) => {
const user = await MyModel.findOne({email: req.body.email})
.then(exUs => {return exUs})
if (user == null) {
return res.status(400).send('no user')
}
try{
if(await bcrypt.compare(req.body.password, user.password)){
res.send('succ')
} else {
res.send('not succ')
}
} catch {
res.status(500).send()
}
})
【问题讨论】:
-
你确定它不是来自这里:
return res.status(400).send('no user')在你的/login端点? -
是的,它来自那里。问题出在 CORS 政策中。
标签: node.js reactjs mongodb express mongoose