Node.js POST 400错误请求、React、Node/Express、MongoDB
我正在学习构建一个简单的MERN应用程序来获取用户数据并将其上传到mongoDB集合,但我似乎不明白为什么在尝试发布用户数据时会收到400个错误请求。它当前正在本地服务器上运行。我目前找不到一个能直接解决我的问题的帖子 以下是数据模式的my data.js:Node.js POST 400错误请求、React、Node/Express、MongoDB,node.js,mongodb,mern,Node.js,Mongodb,Mern,我正在学习构建一个简单的MERN应用程序来获取用户数据并将其上传到mongoDB集合,但我似乎不明白为什么在尝试发布用户数据时会收到400个错误请求。它当前正在本地服务器上运行。我目前找不到一个能直接解决我的问题的帖子 以下是数据模式的my data.js: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const data = new Schema( { x: Number,
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后端:
// 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;
import React,{Component}来自“React”;
从“axios”导入axios;
类应用程序扩展组件{
状态={
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:伊瓦尔,
z:zVal,
r:rVal,
g:gVal,
b:bVal
})
。然后(响应=>{
console.log(响应)
})
.catch(错误=>{
console.log(error.response)
});
//重置状态
//这是我的国家({
//x:0,,
//y:0,
//z:0,
//r:0,
//g:0,
//b:0
// })
};
//用户界面
render(){
返回(
请输入x、y、z和r、g、b的所有适用值
X
this.setState({x:e.target.value})占位符=“0”样式={{width:“40px”}}/>
Y
this.setState({y:e.target.value})占位符=“0”样式={{width:“40px”}}/>
Z
this.setState({z:e.target.value})占位符=“0”样式={{width:“40px”}}/>
R
this.setState({r:e.target.value})占位符=“0”样式={{width:“40px”}}/>
G
this.setState({g:e.target.value})占位符=“0”样式={{width:“40px”}}/>
B
this.setState({b:e.target.value})占位符=“0”样式={{width:“40px”}}/>
this.addData(this.state.x,this.state.y,this.state.z,this.state.r,this.state.g,this.state.b)}>
添加
);
}
}
导出默认应用程序;
根据Google Chrome中的控制台,这就是我收到错误的地方:
我目前不确定我为什么会收到这个错误,罪魁祸首在哪里,我能做些什么来修复它
EDIT1:已使用错误消息进行编辑。有两个主要问题阻止代码工作: 您没有正确地从data.js导出架构: 更改您的模块。导出自
module.exports = mongoose.model("data", DataSchema);
到
您在此处将架构作为数据引用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模块:
您是否尝试打印错误消息?而不是当你遇到错误时仅仅返回400。如果用该错误更新问题,则可能更容易进行故障排除。使用完整的错误消息进行编辑。它似乎指向xhr.js第173行,告诉它加载资源失败,因此出现了400错误。但这不是我所指的错误。这并不是一个真正的错误,因为您的nodejs代码返回400。这是预期的效果。将console.log(err)添加到此行-.catch(err=>{console.log(err);res.status(400).send(“无法保存到数据库”);});您会在nodejs控制台上看到错误。您是否尝试使用Postman或Curl测试Express API?根据Nick的建议,是cors没有在我这边正确实现。事实证明是cors工作不正常。这是我自己的错误。还修复了其他各个方面。将cors下载到我的后端后,它开始正常工作。
// bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));