如何使用Node.js API和React.js将表单数据从网页发布到服务器?

时间:2019-07-09 15:24:40

标签: javascript node.js reactjs

文件

-Server.js

-ClientFolder包含以下内容

  • 公共

  • src包含React组件文件(Register.js)

  • routes文件夹包含(users.js)

我的package.json文件中也设置了代理服务器。

我在React组件(Register.js)中创建了一个处理表单数据的表单,由于在浏览器控制台中收到以下错误,我无法将数据从表单发布到服务器。

无法加载资源:服务器响应状态为404(未找到) index.js:1375

错误:语法错误:JSON中位置0以外的意外令牌<< / p>

Server.js

var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');

var cors = require('cors');
var app = express();

//---- Routes---

var register = require('./routes/users');

// ------------------MySQL Connection ----------------

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'sportsappdb'
});

connection.connect(function(err) {
  if (!err) {
    console.log('Database is connected');
  } else {
    console.log('Error while connecting with database');
  }
});
// ------------------------------------------------

//Init Middleware
app.use(express.json({ extended: false }));
app.get('/', (req, res) => res.send('API Running')); // Test API

app.use(
  bodyParser.urlencoded({
    extended: true
  })
);

app.use(
  session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
  })
);

// Routes
app.use('/users', require('./routes/users'));

const PORT = process.env.PORT || 5000; // Environment variable or port 5000

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Routes / user.js

const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

router.use(
  bodyParser.urlencoded({
    extended: true
  })
);


router.use(bodyParser.json());

router.post('/', function(request, response) {
  var user = {
    username: req.body.username,
    email: req.body.email,
    password: req.body.password,
    userType: req.body.userType,
    team: req.body.team
    // created: today,
    // modified: today
  };

  connection.query('INSERT INTO players SET ?', user, function(
    error,
    results,
    fields
  ) {
    if (error) {
      console.log('error occurred', error);
      res.send({
        code: 400,
        failed: 'error occurred'
      });
    } else {
      console.log('The solution is: ', results);
      res.send({
        code: 200,
        success: 'user registered successfully'
      });
    }
  });
});

module.exports = router;

注册组件

import React, { Component } from 'react';

class RegisterComponent extends React.Component {
  constructor() {
    super();

    this.state = {
      username: '',
      username: '',
      email: '',
      password: '',
      userType: '',
      team: ''
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  //Submit handling
  handleSubmit(event) {
    event.preventDefault();

    const formData = {
      username: this.state.username,
      email: this.state.email,
      password: this.state.password,
      userType: this.state.userType,
      team: this.state.team
    };

    //Fetch API Post method
    fetch('/users', {
      method: 'POST',
      body: JSON.stringify(formData), // data can be `string` or {object}!
      headers: { 'Content-Type': 'application/json' }
    })
      .then(res => res.json())
      .catch(error => console.error('Error:', error))
      .then(response => console.log('Success:', response));
  }

  //Username - User Form handling
  handleUsernameChange = event => {
    this.setState(
      {
        username: event.target.value
      },
      () => {
        this.validateUsername();
      }
    );
  };

  //Username - Input Validation
  validateUsername = () => {
    const { username } = this.state;
    this.setState({
      usernameError:
        username.length > 3
          ? null
          : 'Your username must be longer than 3 characters'
    });
  };

  //Email - User Form handling
  handleEmailChange = event => {
    this.setState(
      {
        email: event.target.value
      },
      () => {
        this.validateEmail();
      }
    );
  };

  //Email - Input Validation
  validateEmail = () => {
    const { email } = this.state;
    this.setState({
      emailError:
        email.length > 3
          ? null
          : 'Your email address must be longer than 3 characters and contain an @ symbol'
    });
  };

  //Password - User Form handling
  handlePasswordChange = event => {
    this.setState(
      {
        password: event.target.value
      },
      () => {
        this.validatePassword();
      }
    );
  };

  //Password - Input Validation
  validatePassword = () => {
    const { password } = this.state;
    this.setState({
      passwordError:
        password.length > 3
          ? null
          : 'Your password must be longer than 3 characters'
    });
  };

  //UserType - User Form handling
  handleUserTypeChange = event => {
    this.setState(
      {
        userType: event.target.value
      }
      // () => {
      //   this.validateUserType();
      // }
    );
  };

  //Team - User Form handling
  handleTeamChange = event => {
    this.setState(
      {
        team: event.target.value
      },
      () => {
        this.validateTeam();
      }
    );
  };

  //Team - Input Validation
  validateTeam = () => {
    const { team } = this.state;
    this.setState({
      teamError:
        team.length > 1
          ? null
          : 'Your username must be longer than 1 characters'
    });
  };

  //JSX REGISTRATION FORM onSubmit={this.handleSubmit}>
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className='form-group'>
          <label htmlFor='username'>Enter your username</label>
          <input
            id='username'
            className={`form-control ${
              this.state.usernameError ? 'is-invalid' : ''
            }`}
            type='text'
            onChange={this.handleUsernameChange}
            onBlur={this.validateUsername}
            required
          />

          <div className='invalid-feedback'>{this.state.usernameError}</div>
        </div>

        <div className='form-group'>
          <label htmlFor='email'>Enter your email</label>
          <input
            id='email'
            className={`form-control ${
              this.state.emailError ? 'is-invalid' : ''
            }`}
            type='email'
            onChange={this.handleEmailChange}
            onBlur={this.validateEmail}
            required
          />
          <div className='invalid-feedback'>{this.state.emailError}</div>
        </div>

        <div className='form-group'>
          <label htmlFor='password'>Enter your password</label>
          <input
            id='password'
            type='password'
            onChange={this.handlePasswordChange}
            onBlur={this.validatePassword}
            className={`form-control ${
              this.state.passwordError ? 'is-invalid' : ''
            }`}
            required
          />
          <div className='invalid-feedback'>{this.state.passwordError}</div>
        </div>

        <div className='form-group'>
          <label htmlFor='role'>Pick your current role within the team:</label>
          <select
            id='userType'
            // value={this.state.userType}
            onChange={this.handleUserTypeChange}
            className='form-control'
            required
          >
            <option value='Staff'>Staff</option>
            <option value='Player'>Player</option>
          </select>

          <div className='invalid-feedback'>{this.state.userTypeError}</div>
        </div>
        {/* Should this be populated when we get users instead of entering the teamName */}
        <div className='form-group'>
          <label htmlFor='team'>Enter your Team</label>
          <input
            id='team'
            className={`form-control ${
              this.state.TeamError ? 'is-invalid' : ''
            }`}
            type='text'
            onChange={this.handleTeamChange}
            onBlur={this.validateTeam}
            required
          />

          <div className='invalid-feedback'>{this.state.TeamError}</div>
        </div>
        <button>Register</button>
      </form>
    );
  }
}

export default RegisterComponent;

0 个答案:

没有答案