node.js - POST 400 错误请求、React、Node/Express、MongoDB
问题描述
我正在学习构建一个简单的 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;
根据谷歌浏览器中的控制台,这是我收到错误的地方:
我目前不确定为什么会收到此错误,罪魁祸首在哪里以及我能做些什么来解决它。
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 模块以获取更多设置选项:
推荐阅读
- reactjs - Service Worker 是如何工作的?
- matlab - MATLAB:计算真实 Elo 性能等级的函数
- mongoose - 使用动态值更新模型
- bash - 从测试文件中读取命令并执行
- javascript - Convert jQuery which shows divs to plain JS
- javascript - 如何在悬停时在右侧显示弹出窗口?
- html - 如何将查询从表单传递到wordpress中的下拉列表?
- javascript - ExpiredKeyMapError - 即使我生成新的 API 仍然错误
- excel - 如果列包含 Y 连接标题
- django - 如何在 django CMS 中处理 meta_url,它不是 django CMS 门户中的可配置参数