вопрос в значительной степени объясняет, что я испытываю в своем коде.
Я опубликую часть соответствующего кода из моего бэкэнда, а также мой код реакции внешнего интерфейса, откуда я отправляю свои запросы ->
server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 4000;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const playerRoutes = express.Router();
let Player = require('./player.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/playerDB', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function () {
console.log("MongoDB database connection established successfully");
});
playerRoutes.route('/').get(function (req, res) {
Player.find(function (err, todos) {
if (err) {
console.log(err);
} else {
res.json(todos);
}
});
});
playerRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Player.findById(id, function(err, todo) {
res.json(todo);
});
});
playerRoutes.route('/add').post(function (req, res) {
let player = new Player(req.body);
player.save()
.then(todo => {
res.status(200).json({ 'player': 'player added successfully' });
})
.catch(err => {
res.status(400).send('adding new player failed');
});
});
playerRoutes.route('/update/:id').post(function(req, res) {
Player.findById(req.params.id, function(err, todo) {
if (!player)
res.status(404).send('player data is not found');
else
player.player_name = req.body.player_name;
player.player_description = req.body.player_description;
player.player_position = req.body.player_position;
player.player_age=req.body.player_age;
player.player_club=req.body.player_club;
player.player_=req.body.player_;
player.player_isactive = req.body.player_isactive;
player.player_completed = req.body.player_completed;
player.save().then(player => {
res.json('Player updated');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
app.use('/playerDB', playerRoutes);
//module.exports = mongoose.model('playerDB', playerDB);
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);
});
Моя модель класса player.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Player = new Schema({
player_name: {
type: String
},
player_description: {
type: String
},
player_position: {
type: String
},
player_age: {
type: String
},
player_club: {
type: String
},
player_: {
type: String
},
player_isactive: {
type: Boolean
},
player_completed: {
type: Boolean
}
});
module.exports = mongoose.model('player', Player);
Теперь после запуска моего бэкэнда с помощью nodemon server и вызывая 2 exe-файла, mongo.exe и mongod.exe, я отправляю запрос в бэкэнд, чтобы добавить новую запись в мою базу данных mongodb.Соответствующий код для этого ->
create-player.component.js
import React, { Component } from 'react';
import axios from 'axios';
export default class CreatePlayers extends Component {
constructor(props)
{
super(props);
this.onChangePlayerName = this.onChangePlayerName.bind(this);
this.onChangePlayerDescription = this.onChangePlayerDescription.bind(this);
this.onChangePlayerPosition = this.onChangePlayerPosition.bind(this);
this.onChangePlayerAge = this.onChangePlayerAge.bind(this);
this.onChangePlayerClub = this.onChangePlayerClub.bind(this);
this.onChangePlayer_ = this.onChangePlayer_.bind(this);
this.onChangePlayerIsActive = this.onChangePlayerIsActive.bind(this);
this.onChangePlayerCompleted = this.onChangePlayerCompleted.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
player_name: '',
player_description: '',
player_position: '',
player_age: '',
player_club:'',
player_: '',
player_isactive: false,
player_completed: false
}
}
onChangePlayerName(e) {
this.setState({
player_name: e.target.value
});
}
onChangePlayerDescription(e) {
this.setState({
player_description: e.target.value
});
}
onChangePlayerPosition(e) {
this.setState({
player_position: e.target.value
});
}
onChangePlayerAge(e) {
this.setState({
player_age: e.target.value
});
}
onChangePlayerClub(e) {
this.setState({
player_club: e.target.value
});
}
onChangePlayer_(e) {
this.setState({
player_: e.target.value
});
}
onChangePlayerIsActive(e) {
this.setState({
player_isactive: e.target.value
});
}
onChangePlayerCompleted(e) {
this.setState({
player_completed: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const newPlayer = {
player_name: this.state.player_name,
player_description: this.state.player_description,
player_position: this.state.player_position,
player_age: this.state.player_age,
player_club: this.state.player_club,
player_: this.state.player_,
player_isactive: this.state.player_isactive,
player_completed: this.state.player_completed
}
axios.post('http://localhost:4000/playerDB/add', newPlayer)
.then(res => console.log(res.data));
this.setState({
player_name: '',
player_description: '',
player_position: '',
player_age: '',
player_club:'',
player_: '',
player_isactive: false,
player_completed: false
})
}
render() {
return (
<div style={{ marginTop: 20 }}>
<h3 className="txt-blue" style={{marginLeft:15}}>Create New Player</h3>
<form className="form-class" onSubmit={this.onSubmit}>
<div className="form-group">
<label>Name: </label>
<input type="text"
className="form-control"
value={this.state.player_name}
onChange={this.onChangePlayerName}
/>
</div>
<div className="form-group">
<label>Player Description: </label>
<input type="text"
className="form-control"
value={this.state.player_description}
onChange={this.onChangePlayerDescription}
/>
</div>
<div className="form-group">
<label>Position: </label>
<input type="text"
className="form-control"
value={this.state.player_position}
onChange={this.onChangePlayerPosition}
/>
</div>
<div className="form-group">
<label>Age: </label>
<input type="text"
className="form-control"
value={this.state.player_age}
onChange={this.onChangePlayerAge}
/>
</div>
<div className="form-group">
<label>Club: </label>
<input type="text"
className="form-control"
value={this.state.player_club}
onChange={this.onChangePlayerClub}
/>
</div>
<div className="form-group">
<label>Player Status: </label>
<input type="text"
className="form-control"
value={this.state.player_}
onChange={this.onChangePlayer_}
/>
</div>
<div className="form-check">
<input className="form-check-input"
type="radio"
name="isactive"
id="isactive"
value="Active"
checked={this.state.player_isactive === 'Active'}
onChange={this.onChangePlayerIsActive}
/>
<label className="form-check-label">Active</label>
</div>
<div className="form-check" style={{marginTop:20}}>
<input className="form-check-input"
type="radio"
name="completed"
id="completed"
value="Active"
checked={this.state.player_completed === 'Active'}
onChange={this.onChangePlayerCompleted}
/>
<label className="form-check-label">Completed</label>
</div>
<div className="form-group" style={{marginTop:20}}>
<input type="submit" value="Create Player" className="btn btn-primary" />
</div>
</form>
</div>
)
}
}
Казалось бы, довольно просто.или так я бы подумал.Но я получаю следующую ошибку при сохранении
http://localhost:4000/playerDB/add 400 (Bad Request)
Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
Я не уверен, как отлаживать приложение MERN, в частности, часть nodejs бэкэнда.Мой опыт работы с React и Mongo теперь 1 неделя.Главным образом исследуя только вещи.Можете ли вы сказать мне, какая часть моего кода могла пойти не так?Я хочу знать 2 вещи здесь -> 1. ошибка моего кода 2. способ отладки этого сам [я использую VS2017]
Нужна быстрая помощь по этому вопросу,