gpt4 book ai didi

node.js - 无法将数据从 React Js 发布到 Node js

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:18 25 4
gpt4 key购买 nike

我无法将我的数据从React Js发布到Node Js,我一直在寻找多个资源但无法解决它

这是我的完整代码。

这是我的 react 文件“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}'));

这是我的 Node 文件“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 (

最佳答案

正如您从包含的网络请求中看到的:

xhr.js:178 POST http://localhost:3000/api/users/register 404 (Not Found)

您正在将请求发送到 localhost:3000。正如您提到的,您的 Node 服务器在端口 5000 上运行。这意味着您的请求应该发送到那里。

现在您在这种情况下有多种选择。

1) 启用 Cross-Origin Resource Sharing 。这将允许您将请求从一个源发送到另一个源。

2) 让您的 Node 服务器为您的前端代码提供服务,这样您就无需处理单独的源。

我个人更喜欢选项 1,因为它可以帮助我区分我的担忧。

由于您使用的是 Express,因此您需要将其添加到服务器代码中:

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

并且您的客户端代码(React)应该更新以像这样调用正确的源

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));
}
}

关于node.js - 无法将数据从 React Js 发布到 Node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51986299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com