I am receiving this error when attempting to post a new entry into a database I have created, called Doctors.
My server.js looks like this:
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:
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.
Please change your server.js to this:
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
Cannot POST /doctors in express means that a particular route doesn't exist.
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
.
I just tested this successfully.. It appears the issue is with your Mongo
code..
Try this, if it works, you know the issue is with the Mongo
section.
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..
Folder Structure:
root
|- database
|- index.js
|- models
|- someModel.js
In /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
:
'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. Thanks for the help anyway! Hope this thread helps someone else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.