[英]Receiving a Cannot POST error when attempting to post data in a rest client
I am receiving this error when attempting to post a new entry into a database I have created, called Doctors.我在尝试将新条目发布到我创建的名为 Doctors 的数据库中时收到此错误。
My server.js looks like this:我的 server.js 看起来像这样:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri, { useNewUrlParser: true });
const morgan = require('morgan');
var Doctor = require('./www/js/user.js');
app.use(bodyParser.json());
app.use(express.static('www'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
const mongoURL = 'mongodb://localhost:27017/app';
mongoose.connect(mongoURL, function (err) {
if (err) {
console.log('Not connected to the database:' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
app.post('/doctors', function (req, res) {
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
});
// Configure port
const port = process.env.PORT || 8080;
// Listen to port
app.listen(port);
console.log(`Server is running on port: ${port}`);
app.get('*', function (req, res) {
res.sendfile('./www/index.html');
});
My user.js, which is my schema, looks like this:我的 user.js,即我的架构,如下所示:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var DoctorSchema = new Schema({
doctorID: {type: Number, required: true, unique: true},
password: {type: String, required: true}
});
//encrypt password
DoctorSchema.pre('save', function(next){
var doctor = this;
bcrypt.hash(doctor.password, null, null, function(err, hash){
if (err) return next(err);
doctor.password = hash;
next();
});
})
module.exports = mongoose.model('Doctor', DoctorSchema);
When attempting to post, I get this error.尝试发布时,我收到此错误。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /doctors</pre>
</body>
</html>
I don't understand why I'm getting this particular error.我不明白为什么我会收到这个特定的错误。 I can get data from /doctors with no issues, I just can't post to it.
我可以毫无问题地从 /doctors 获取数据,只是无法发布。
Please change your server.js to this:请将您的 server.js 更改为:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(uri, { useNewUrlParser: true });
const morgan = require('morgan');
var Doctor = require('./www/js/user.js');
app.use(bodyParser.json());
app.use(express.static('www'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
const mongoURL = 'mongodb://localhost:27017/app';
mongoose.connect(mongoURL, function (err) {
if (err) {
console.log('Not connected to the database:' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
app.post('/doctors', function (req, res) {
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
});
// Configure port
const port = process.env.PORT || 8080;
app.get('*', function (req, res) {
res.sendfile('./www/index.html');
});
app.listen(port, function() {
console.log(
`Server listening on port ${port}!`
);
});
EDIT - Just correcting an issue in the .listen编辑- 只是更正 .listen 中的问题
Cannot POST /doctors in express means that a particular route doesn't exist.不能 POST /doctors in express 意味着特定的路由不存在。
Can you show more code, on what port are you posting ?你能展示更多的代码,你在哪个端口发布?
Did you set the right content type in the request?您是否在请求中设置了正确的内容类型?
Content-Type: application/json
Else, the req.body.doctorID
will return undefined
.否则,
req.body.doctorID
将返回undefined
。
I just tested this successfully.. It appears the issue is with your Mongo
code..我刚刚成功测试了这个..看来问题出在你的
Mongo
代码上..
Try this, if it works, you know the issue is with the Mongo
section.试试这个,如果它有效,你就知道问题出在
Mongo
部分。
This is how I am sending the requests.. using Postman这就是我发送请求的方式..使用邮递员
This shows how I am able to receive the request:这显示了我如何能够接收请求:
const express = require('express');
const bodyParser = require('body-parser');
//const mongoose = require('mongoose');
const app = express();
const router = express.Router();
//const MongoClient = require('mongodb').MongoClient;
//const client = new MongoClient(uri, { useNewUrlParser: true });
//const morgan = require('morgan');
//var Doctor = require('./www/js/user.js');
app.use(bodyParser.json());
app.use(express.static('www'));
//app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ 'extended': 'true' }));
app.use(bodyParser.json());
//const mongoURL = 'mongodb://localhost:27017/app';
/*
mongoose.connect(mongoURL, function (err) {
if (err) {
console.log('Not connected to the database:' + err);
} else {
console.log('Successfully connected to MongoDB');
}
});
*/
app.post('/doctors', function (req, res) {
console.log(req.body);
res.status(200).send();
/*
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
*/
});
// Configure port
const port = process.env.PORT || 8080;
// Listen to port
app.listen(port);
console.log(`Server is running on port: ${port}`);
app.get('*', function (req, res) {
res.sendfile('./www/index.html');
});
To expand on this answer.. I usually configure Mongoose
in the following manner..为了扩展这个答案..我通常按以下方式配置
Mongoose
..
Folder Structure:文件夹结构:
root
|- database
|- index.js
|- models
|- someModel.js
In /root/database/index.js
:在
/root/database/index.js
:
'use strict'
const mongoose = require('mongoose');
const mongoBaseUrl = `mongodb://server:27017/collection`;
const mongoDB = mongoose.createConnection(mongoBaseUrl, { useNewUrlParser: true, promiseLibrary: global.Promise });
mongoose.set('useCreateIndex', true) // needed to suppress errors
module.exports = mongoDB;
Then in /root/models/someModel.js
:然后在
/root/models/someModel.js
:
'use strict'
const mongoose = require('mongoose');
const mongoConnection = require('../database');
const modelName = "SomeModel";
const collection = "SomeCollection";
const databaseName = "SomeDatabase";
const myDatabase = mongoConnection.useDb(databaseName);
const SomeSchema = new mongoose.Schema({
// Schema data here
})
module.exports = myDatabase.model(modelName, SomeSchema, collection) // (database, schema, collection)
Then to use it in your routes:然后在您的路线中使用它:
const Doctor = require('./models/someModel.js');
app.post('/route/', (req, res, next) => {
var doctor = new Doctor();
doctor.doctorID = req.body.doctorID;
doctor.password = req.body.password;
doctor.save();
res.send('doctor created');
});
Something to that effect.那种效果的东西。 Hope this helps.
希望这可以帮助。
It turns out the issue was with neither, we had a duplicated server.js, and it was referencing the incorrect one.事实证明,两者都不是问题,我们有一个重复的 server.js,它引用了不正确的。 Thanks for the help anyway!
无论如何感谢您的帮助! Hope this thread helps someone else.
希望这个线程可以帮助其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.