简体   繁体   中英

400 bad Request using axios

I have an issue with my web app. FrontEnd : React Backend: NodeJS Database : MongoDB

I have do a registration form and this one is poster in the node JS server via axios and a model of mongoDB. This one works very well !

I have do the same thing to submit an classified ads with the same protocol and it's doesn't works and give me the error 400 BAD REQUEST. I have controlled the model, the state, but apparently all is good.

Here the model for the ads :

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
pseudo: {
    type: String,
    required: true
},

age: {
    type: String,
    required: true
},

telephone: {
    type: String,
    required: true
},

langue: {
    type: String,
    required: true
},

adresse: {
    type: String,
    required: true
},

ethnie: {
    type: String,
    required: true
},
yeux: {
    type: String,
    required: true
},

taille: {
    type: String,
    required: true
},
cheveux: {
    type: String,
    required: true
},
forme: {
    type: String,
    required: true
},

service: {
    type: String,
    required: true
},

lieu: {
    type: String,
    required: true
},

sexe: {
    type: String,
    required: true
},
tarif: {
    type: String,
    required: true
},    

paiement: {
    type: String,
    required: true
},           
description: {
    type: String,
    required: true
},
site: {
    type: String,
    required: true
}

       });
    module.exports = mongoose.model('Todo', Todo);

Here is the server.js :

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const validateRegisterInput = require('./validation/register');
const passport = require('passport');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const config = require('./data/db')
const PORT = 4000; // PORT dur serveur Node

// Utilisation du modèle de bdd
const Todo = require('./todo.model');
const User = require('./user.model');

app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
() => {console.log('Database is connected') },
err => { console.log('Cannot connect to the database'+ err)}
);
// Connection à la base donnée
/*mongoose.connect('mongodb://127.0.0.1:27017/todos', { useNewUrlParser: 
true });
const connection = mongoose.connection;
// Vérification de la connection à la base de données
connection.once('open', function() {
console.log("MongoDB database connection established successfully");
})*/

app.use(passport.initialize());
require('./passport')(passport);

// Affichage de la liste d'élément
todoRoutes.route('/').get(function(req, res) {
Todo.find(function(err, todos) {
    if (err) {
        console.log(err);
    } else {
        res.json(todos);
    }
});
});
// Affichage d'un élément
todoRoutes.route('/:id').get(function(req, res) {
let id = req.params.id;
Todo.findById(id, function(err, todo) {
    res.json(todo);
});
});
// Modification de la base de donnée lors de l'update d'un composant
todoRoutes.route('/update/:id').post(function(req, res) {
Todo.findById(req.params.id, function(err, todo) {
    if (!todo)
        res.status(404).send("data is not found");
    else
        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;

        todo.save().then(todo => {
            res.json('Todo updated!');
        })
        .catch(err => {
            res.status(400).send("Update not possible");
        });
});
});
// Créer un nouvel élément
todoRoutes.route('/add').post(function(req, res) {

let todo = new Todo({
    pseudo: req.body.pseudo,
    age: req.body.age,
    telephone: req.body.telephone,
    langue: req.body.langue,
    adresse: req.body.adresse,
    ethnie: req.body.ethnie,
    yeux: req.body.yeux,
    taille: req.body.taille,
    cheveux: req.body.cheveux,
    forme: req.body.forme,
    service: req.body.service,
    lieu: req.body.lieu,
    sexe: req.body.sexe,
    tarif: req.body.tarif,
    paiement: req.body.paiement,
    description: req.body.description,
    site: req.body.site
});
todo.save()
    .then(todo => {
        req.status(200).json({'todo': 'todo added successfully'});
    })
    .catch(err => {
        res.status(400).send('adding new todo failed');
    });


});

todoRoutes.route('/register').post(function(req, res) {

const { errors, isValid } = validateRegisterInput(req.body);

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 exists'
        });
    }
    else {

        const newUser = new User({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email,
            password: req.body.password
        });

        bcrypt.genSalt(10, (err, salt) => {

            if(err) console.error('There was an error', err);
            else {

                bcrypt.hash(newUser.password, salt, (err, hash) => {
                    if(err) console.error('There was an error', err);
                    else {

                        newUser.password = hash;

                        newUser
                            .save()
                            .then(user => {
                                res.json(user)
                            }); 
                    }
                });
            }
        });
    }
});
});

todoRoutes.post('/login', (req, res) => {

const { errors, isValid } = validateLoginInput(req.body);

if(!isValid) {
    return res.status(400).json(errors);
}

const email = req.body.email;
const password = req.body.password;

User.findOne({email})
    .then(user => {
        if(!user) {
            errors.email = 'User not found'
            return res.status(400).json(errors);
        }
        bcrypt.compare(password, user.password)
                .then(isMatch => {
                    if(isMatch) {
                        const payload = {
                            id: user.id,
                            name: user.name
                        }
                        jwt.sign(payload, 'secret', {
                            expiresIn: 3600
                        }, (err, token) => {
                            if(err) console.error('There is some error in 
token', err);
                            else {
                                res.json({
                                    success: true,
                                    token: `Bearer ${token}`
                                });
                            }
                        });
                    }
                    else {
                        errors.password = 'Incorrect Password';
                        return res.status(400).json(errors);
                    }
                });
    });
});
todoRoutes.get('/me', passport.authenticate('jwt', { session: false }), 
(req, res) => {
return res.json({
    id: req.user.id,
    name: req.user.name,
    email: req.user.email
}); 
});
app.use('/todos', todoRoutes);

// Vérification du port
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});

here the create-announce.js (component) :

import React, { Component } from 'react';
import axios from 'axios';
import Header from "./header";
import Footer from "./footer";


export default class CreateAnnounce extends Component {
    // déclaration du constructor
    constructor(props) {
        super(props);

        this.onChangePseudo = this.onChangePseudo.bind(this);
        this.onChangeAge = this.onChangeAge.bind(this);
        this.onChangeTelephone = this.onChangeTelephone.bind(this);
        this.onChangeLangue = this.onChangeLangue.bind(this);
        this.onChangeAdresse = this.onChangeAdresse.bind(this);
        this.onChangeEthnie = this.onChangeEthnie.bind(this);
        this.onChangeYeux = this.onChangeYeux.bind(this);
        this.onChangeTaille = this.onChangeTaille.bind(this);
        this.onChangeCheveux = this.onChangeCheveux.bind(this);
        this.onChangeForme = this.onChangeForme.bind(this);
        this.onChangeService = this.onChangeService.bind(this);
        this.onChangeLieu = this.onChangeLieu.bind(this);
        this.onChangeSexe = this.onChangeSexe.bind(this);
        this.onChangeTarif = this.onChangeTarif.bind(this);
        this.onChangePaiement = this.onChangePaiement.bind(this);
        this.onChangeDescription = this.onChangeDescription.bind(this);
        this.onChangeSite = this.onChangeSite.bind(this);
        this.onSubmit = this.onSubmit.bind(this);

        // déclaration du state
        this.state = {
            pseudo: '',
            age: '',
            telephone: '',
            langue: '',
            adresse: '',
            ethnie: '',
            yeux: '',
            taille: '',
            cheveux: '',
            forme: '',
            service: '',
            lieu: '',
            sexe: '',
            tarif: '',
            paiement: '',
            description: '',
            site: ''
        }
    }
    // fonction pour l'update des données dans la BDD
    onChangePseudo(e) {
        this.setState({
            pseudo: e.target.value
        });
    }

    onChangeAge(e) {
        this.setState({
            age: e.target.value
        });
    }

    onChangeTelephone(e) {
        this.setState({
            telephone: e.target.value
        });
    }

    onChangeLangue(e) {
        this.setState({
            langue: e.target.value
        });
    }

    onChangeAdresse(e) {
        this.setState({
            adresse: e.target.value
        });
    }


    onChangeEthnie(e) {
        this.setState({
            ethnie: e.target.value
        });
    }

    onChangeYeux(e) {
        this.setState({
            yeux: e.target.value
        });
    }

    onChangeCheveux(e) {
        this.setState({
            cheveux: e.target.value
        });
    }

    onChangeTaille(e) {
        this.setState({
            taille: e.target.value
        });
    }

    onChangeForme(e) {
        this.setState({
            forme: e.target.value
        });
    }

    onChangeService(e) {
        this.setState({
            service: e.target.value
        });
    }

    onChangeLieu(e) {
        this.setState({
            lieu: e.target.value
        });
    }

    onChangeSexe(e) {
        this.setState({
            sexe: e.target.value
        });
    }

    onChangeTarif(e) {
        this.setState({
            tarif: e.target.value
        });
    }

    onChangePaiement(e) {
        this.setState({
            paiement: e.target.value
        });
    }
    onChangeDescription(e) {
        this.setState({
            description: e.target.value
        });
    }

    onChangeSite(e) {
        this.setState({
            site: e.target.value
        });
    }




    fileSelectedHandler = event => {
        console.log(event);
    }
    fileUploadHandler(e) {
        axios.post();
    }

    onSubmit(e) {
        e.preventDefault();

        console.log(`Form submitted:`);
        console.log(`pseudo: ${this.state.pseudo}`);
        console.log(`age: ${this.state.age}`);
        console.log(`telephone: ${this.state.telephone}`);
        console.log(`langue: ${this.state.langue}`);
        console.log(`adresse: ${this.state.adresse}`);
        console.log(`ethnie: ${this.state.ethnie}`);
        console.log(`yeux: ${this.state.yeux}`);
        console.log(`taille: ${this.state.taille}`);
        console.log(`cheveux: ${this.state.cheveux}`);
        console.log(`forme: ${this.state.forme}`);
        console.log(`service: ${this.state.service}`);
        console.log(`lieu: ${this.state.lieu}`);
        console.log(`sexe: ${this.state.sexe}`);
        console.log(`tarif: ${this.state.tarif}`);
        console.log(`paiement: ${this.state.paiement}`);
        console.log(`description: ${this.state.description}`);
        console.log(`site: ${this.state.site}`);

        const newTodo = {
            pseudo: this.state.pseudo,
            age: this.state.age,
            telephone: this.state.telephone,
            langue: this.state.langue,
            adresse: this.state.adresse,
            ethnie: this.state.ethnie,
            yeux: this.state.yeux,
            taille: this.state.taille,
            cheveux: this.state.cheveux,
            forme: this.state.forme,
            service: this.state.service,
            lieu: this.state.lieu,
            sexe: this.state.sexe,
            tarif: this.state.tarif,
            paiement: this.state.paiement,
            description: this.state.description,
            site: this.state.site
        };

        console.log(newTodo);

        // envoi des données via axios
        axios.post('http://localhost:4000/todos/add', newTodo)
            .then(res => console.log(res.data))
            .catch(err => {
                console.log(err);
            })
        this.setState({
            pseudo: '',
            age: '',
            telephone: '',
            langue: '',
            adresse: '',
            ethnie: '',
            yeux: '',
            taille: '',
            cheveux: '',
            forme: '',
            service: '',
            lieu: '',
            sexe: '',
            tarif: '',
            paiement: '',
            description: '',
            site: ''
        })
    }

    render() {
        return (
            <>
<Header />

            <div style={{marginTop: 10}}>
                <h3>Mon profil</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group"> 
                        <label>Pseudo: </label>
                        <input  type="text"
                                className="form-control"
                                value={this.state.pseudo}
                                onChange={this.onChangePseudo}
                                />
                                <label> Age: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.age}
                                onChange={this.onChangeAge}
                                />
                                <label> Téléphone: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.telephone}
                                onChange={this.onChangeTelephone}
                                />
                                <label> Langue: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.langue}
                                onChange={this.onChangeLangue}
                                />
                                <label> Adresse: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.adresse}
                                onChange={this.onChangeAdresse}
                                />
                                <label> Sexe: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.sexe}
                                onChange={this.onChangeSexe}
                                />
                                <label> ethnie: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.ethnie}
                                onChange={this.onChangeEthnie}
                                />
                                <label> Couleur des yeux: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.yeux}
                                onChange={this.onChangeYeux}
                                />
                                <label> Couleur des cheveux: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.cheveux}
                                onChange={this.onChangeCheveux}
                                />
                                <label> Taille (en cm): </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.taille}
                                onChange={this.onChangeTaille}
                                />
                                <label> Prix à partir de: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.tarif}
                                onChange={this.onChangeTarif}
                                />
                                <label> forme du corps: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.forme}
                                onChange={this.onChangeForme}
                                />
                                <label> Service proposé: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.service}
                                onChange={this.onChangeService}
                                />
                                <label> Lieu: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.lieu}
                                onChange={this.onChangeLieu}
                                />
                                <label> Paiement: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.paiement}
                                onChange={this.onChangePaiement}
                                />
                                <label> Site internet: </label>
                                <input  type="text"
                                className="form-control"
                                value={this.state.site}
                                onChange={this.onChangeSite}
                                />

                                <label>Ajouter une image: </label>
                                <input type="file" onChange={this.fileSelectedHandler} />
                                <button onClick={this.fileUploadHandler} />
                            </div>
                            <label>Ajouter une Vidéo: </label>
                                <input type="file" onChange={this.fileSelectedHandler} />
                                <button onClick={this.fileUploadHandler} />

                    <div className="form-group">
                        <label>Description: </label>
                        <input 
                                type="text" 
                                className="form-control"
                                value={this.state.description}
                                onChange={this.onChangeDescription}
                                />
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Create Todo" className="btn btn-primary" />
                    </div>
                </form>
            </div>
            <Footer />
            </>
        )
    }
}

Maybe try setting the 'content-type' in the config object of the axios post request?


 axios.post('http://localhost:4000/todos/add', newTodo, {
        headers: {
            'Content-Type': 'application/json'
        }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM