Zariay
Zariay

Reputation: 29

POST 400 Bad request, React, Node/Express, MongoDB

I'm learning to build a simple MERN application to take user data and upload it to a mongoDB collection, and I can't seem to figure out why I'm receiving a 400 BAD REQUEST error when attempting to post the user data. It's currently being run on local server. I'm currently unable to find a post that directly solves my particular issue.

Here is my data.js for the data schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const data = new Schema(
    {
        x: Number,
        y: Number,
        z: Number,
        r: Number,
        g: Number,
        b: Number
    },
    { collection: "cube" }
);

module.exports = mongoose.model("data", DataSchema);

My server.js backend:

// JavaScript source code
const mongoose = require("mongoose");
const express = require("express");
const bodyParser = require("body-parser");
const logger = require("morgan");
const Data = require("./data");
const cors = require("cors");

const API_PORT = 3000;
const app = express();
const router = express.Router();

//MongoDB database
const dbRoute = "mongodb+srv://testuser:[email protected]/test?retryWrites=true";

mongoose.connect(
    dbRoute,  
    { useNewUrlParser:true }
);

let db = mongoose.connection;

db.once("open", () => console.log("Connected to database"));

db.on("error", console.error.bind(console, "MongoDB connection error:"));

// bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger("dev"));

//this is our add method
//add method to add data into database
router.post ("/putData", (req, res) => {
    let data = new Data(req.body);

    data.save()
    .then(data => {
        res.json('Values added successfully');
    })
    .catch(err => {
        res.status(400).send("unable to save to database");
    });
});

app.use("/api", router);
app.use(express.json());

app.listen(API_PORT, () => console.log('Listening on port ${API_PORT}'));

And finally my App.js frontend:

import React, { Component } from "react";
import axios from "axios";

class App extends Component {
    state = {
        x: 0,
        y: 0,
        z: 0,
        r: 0,
        g: 0,
        b: 0
    };

    addData = (xVal, yVal, zVal, rVal, gVal, bVal) => {
        axios.post("http://localhost:3000/api/putData", {
            x: xVal,
            y: yVal,
            z: zVal,
            r: rVal,
            g: gVal,
            b: bVal
        })
        .then(response => { 
            console.log(response)
        })
        .catch(error => {
            console.log(error.response)
        });
// reset state
        // this.setState({
        //     x: 0,
        //     y: 0,
        //     z: 0,
        //     r: 0,
        //     g: 0,
        //     b: 0
        // })

    };

//UI
    render(){
        return (
            <div>  
                <ul>
                    <p> Please enter all applicables values for x, y, z, and r, g, b. </p>
                </ul>
                <div>
                    <label> X </label>
                    <input type="number" min="0" max="360" onChange={e => this.setState({x: e.target.value})} placeholder="0" style={{width:"40px"}} />
                    <label> Y </label>
                    <input type="number" min="0" max="360" onChange={e => this.setState({y: e.target.value})} placeholder="0" style={{width:"40px"}} />
                    <label> Z </label>
                    <input type="number" min="0" max="360" onChange={e => this.setState({z: e.target.value})} placeholder="0" style={{width:"40px"}} />
                    <label> R </label>
                    <input type="number" min="0" max="255" onChange={e => this.setState({r: e.target.value})} placeholder="0" style={{width:"40px"}} />
                    <label> G </label>
                    <input type="number" min="0" max="255" onChange={e => this.setState({g: e.target.value})} placeholder="0" style={{width:"40px"}} />
                    <label> B </label>
                    <input type="number" min="0" max="255" onChange={e => this.setState({b: e.target.value})} placeholder="0" style={{width:"40px"}} />
                    <button onClick={() => this.addData(this.state.x, this.state.y, this.state.z, this.state.r, this.state.g, this.state.b)}>
                    Add
                    </button>
                </div>
            </div>
        );
    }
}

export default App;

According to the console in Google Chrome, this is where I receive the error:

![Full error message

I'm currently unsure why I'm receiving this error, where the culprit lies and what I can do to fix it.

EDIT1: Edited with the error message.

Upvotes: 1

Views: 5640

Answers (1)

Borduhh
Borduhh

Reputation: 2185

There were two main problems that are preventing your code from working:

You're not exporting your Schema from data.js properly:

Change your module.exports from

module.exports = mongoose.model("data", DataSchema);

to

module.exports = mongoose.model("data", data);

You are referencing the schema as data here const data = new Schema(...).

As well you are also getting a CORS error because you have not used it in your server.js. You need to add:

app.use(cors());
app.options('*', cors());

To your server.js file above:

// bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));

That got it working on my localhost. However, I would highly advise against using that setup in a production environment. Check out the CORS module for more setup options:

https://www.npmjs.com/package/cors

Upvotes: 1

Related Questions