我正在学习构建一个简单的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浏览器中的控制台,这是我收到错误的地方:
我目前不确定为什么会收到此错误,罪魁祸首在哪里以及如何解决该错误。
EDIT1:使用错误消息进行编辑。
答案 0 :(得分:0)
有两个主要问题使您的代码无法正常工作:
您没有从data.js中正确导出模式:
更改模块。导出自
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模块以获取更多设置选项: