我无法将我的数据从React Js发布到Node Js,我一直在寻找几种资源,但无法解决
这是我完整的代码。
这是我的反应文件“ Register.js”,运行在端口3000(http://localhost:3000/register)
import React, { Component } from 'react';
import axios from 'axios';
class Register extends Component {
//takes user input
constructor(){
super();
this.state={
name:'',
email:'',
password:'',
password2:'',
errors:{}
}
//joins it to onChange fun
this.onChange=this.onChange.bind(this);
this.onSubmit=this.onSubmit.bind(this);
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
}
onSubmit(s){
s.preventDefault();
const newUser={
name:this.state.name,
email:this.state.email,
password:this.state.password,
password2:this.state.password2
}
axios.post('/api/users/register',newUser)
.then(res=> console.log(res.data))
.catch(err=>console.log(err.response.data));
}
render() {
return (
<div className="home">
<div className="dark-overlay landing-inner text-light">
<div className="container">
<div className="row">
<div className="col-md-12 text-center">
<h1 className="display-4 text-center">Sign Up</h1>
<p className="lead text-center">Create your Profile and start getting noticed by Employers!</p>
<div className="form-group">
<form onSubmit={this.onSubmit}>
<div className="form-group">
<input type="name" placeholder="Name" className="form-control" name="name" value={this.state.name} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="email" placeholder="Email" className="form-control" name="email" value={this.state.email} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="password" placeholder="Password" className="form-control" name="password" value={this.state.password} onChange={this.onChange} />
</div>
<div className="form-group">
<input type="password" placeholder=" Confirm Password" className="form-control" name="password2" value={this.state.password2} onChange={this.onChange}/>
</div>
<hr />
<input type="submit" className="btn btn-lg btn-success"/>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Register;
这是“ server.js”代码:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const users=require('./routes/api/users');
const userprofile=require('./routes/api/userprofile');
const app=express();
//body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//connecting to database
mongoose
.connect(db)
.then(() => console.log('mongo is successfully Connected'))
.catch(err => console.log(err));
//passport middleware
app.use(passport.initialize());
//passsport config
require('./config/passport')(passport);
//testing the server
app.get('/',(req,res)=>res.send('working'));
//using routes for users and userprofile
app.use('/api/users',users);
app.use('/api/userprofile',userprofile);
//to connect to localhost
const port=process.env.PORT || 5000;
app.listen(port,()=> console.log('server running on ${port}'));
这是我的节点文件'users.js',在端口5000上运行
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const keys = require('../../config/keys');
const passport = require('passport');
//bringing input validation
const validatingregister=require('../../validation/register');
const validatingrlogin=require('../../validation/login');
//loading User schema
const User=require('../../models/User');
router.get('/demo', (req, res) => res.json({ msg: 'user api Works' }));
//will check email address if exists or not
router.post('http://localhost:5000/api/users/register',(req,res)=>{
const { errors, isValid } = validatingregister(req.body);
// Checking Validation
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({email:req.body.email})
.then(user=>{
if(user){
return res.status(400).json({email:"email already registered"});
}
//if not then will create newuser
else{
const newUser=new User({
name:req.body.name,
email:req.body.email,
password:req.body.password
});
//bcrypt is for hashing the password of the user
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
}
)}
})
})
//login route
router.post('/login', (req, res) => {
const { errors, isValid } = validatingrlogin(req.body);
// Check Validation for login
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
//finding user by email
User.findOne({ email }).then(user => {
//if no user with this email
if(!user){
return res.status(400).json("No user with this email");
}
//checking pass
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// User Matched
const payload = { id: user.id, name: user.name, avatar: user.avatar }; // Create JWT Payload
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: 'Bearer ' + token
});
}
);
}
else{
res.status(400).json({password:"incorrect password"});
}
})
});
})
router.get(
'/current',
passport.authenticate('jwt', { session: false }),
(req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email
});
})
module.exports = router;
我正在尝试注册用户,但出现错误:
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
(anonymous function)
src/components/auth/Register.js:36
33 |
34 | axios.post('http://localhost:5000/api/users/register',newUser)
35 | .then(res=> console.log(res.data))
> 36 | .catch(err=>console.log(err.response.data));
37 | }
38 | render() {
39 | return (
答案 0 :(得分:3)
从网络请求中您可以看到:
xhr.js:178 POST http://localhost:3000/api/users/register 404 (Not Found)
您正在将请求发送到localhost:3000
。如前所述,您的节点服务器在端口5000
上运行。这意味着您的请求应该发送到那里。
现在在这种情况下您有多种选择。
1)启用Cross-Origin Resource Sharing。 这样您就可以将请求从一个来源发送到另一个来源。
2)让您的Node服务器提供您的前端代码,这样您就无需处理单独的源了。
我个人更喜欢选项1,因为它可以帮助我分开关注点。
由于您使用快递,因此需要将其添加到服务器代码中:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
有关启用CORS支票Enable CORS
的更多信息您的客户代码(反应)应进行更新以调用正确的来源
onSubmit(s){
// your code ...
axios.post('//localhost:5000/api/users/register', newUser)
.then(res=> console.log(res.data))
.catch(err=>console.log(err.response.data));
}
}