node.js - POST 400 错误请求、React、Node/Express、MongoDB

标签 node.js mongodb mern

我正在学习构建一个简单的 MERN 应用程序来获取用户数据并将其上传到 mongoDB 集合,但我似乎无法弄清楚为什么在尝试发布用户数据时收到 400 BAD REQUEST 错误。它当前正在本地服务器上运行。我目前无法找到直接解决我的特定问题的帖子。

这是我的数据架构的 data.js:

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

我的 server.js 后端:

// 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:testuserpw@alexcluster-alfjn.mongodb.net/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}'));

最后是我的 App.js 前端:

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;

根据 Google Chrome 中的控制台,这是我收到错误的地方:

![Full error message

我目前不确定为什么会收到此错误、罪魁祸首在哪里以及我可以采取哪些措施来修复它。

EDIT1:已编辑错误消息。

最佳答案

有两个主要问题导致您的代码无法运行:

您没有正确从 data.js 导出架构:

更改您的 module.exports

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

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

您在此处将架构引用为数据const data = new Schema(...)

此外,您还会收到 CORS 错误,因为您尚未在 server.js 中使用它。您需要添加:

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

到上面的 server.js 文件:

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

这让它在我的本地主机上运行。但是,我强烈建议不要在生产环境中使用该设置。查看 CORS 模块以获取更多设置选项:

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

关于node.js - POST 400 错误请求、React、Node/Express、MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54936409/

相关文章:

javascript - curl机制,在expressjs代码里面

node.js - 在 Yocto 项目的meta-nodejs 中指定nodejs 的版本

Java/mongodb - 如何实现聚合方法以将结果作为游标返回

node.js - mongodb 在使用数字进行文本搜索时性能不佳

reactjs - 为什么我会收到此错误 : Invalid hook call. Hooks can only be called inside of a function component/

javascript - Socket.io emit() 延迟/缓冲区刷新?

node.js - 有人可以帮我理解并解决这个 "Failed to install @parcel/transformer-image"吗? (JS)

mongodb - 使用 Mongodb 的 java 驱动程序,如何在同一字段上搜索多个值?

node.js - 将mern应用程序部署到heroku后路由出现问题

reactjs - Helm 导致在 heroku 上托管的 MERN 应用程序导致错误 : Refused to execute inline script because it violates the following