[ad_1]
I am posting a data to mongoosedb, I check my code seems no bug or typo, but when I send data through app.post()
, it return 400, I check the data can connect to post app.post()
, because I change the return error 400 to 401, the browser say the error is 401.
return error set to 400
POST http://localhost:3000/api/products 400 (Bad Request)
return error set to 401
POST http://localhost:3000/api/products 401 (Unauthorized)
I sure that the db has been connected, because I set something like this
mongoose.connect('<MY key for mongodb>')
.then(() => {
console.log('Successfully connected to MongoDB Atlas!');
})
.catch((error) => {
console.log('Unable to connect to MongoDB Atlas!');
console.error(error);
});
It return Successfully connected to MongoDB Atlas!
when I connect.
what will be the bug?
app.js
const mongoose = require('mongoose');
const Product = require('./models/product');
const app = express();
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use(express.json());
app.post('/api/products', (req, res, next) => {
const product = new Product({
name: req.body.name,
description: req.body.description,
price: req.body.price,
inStock: req.body.inStock,
userId: req.body.userId
});
product.save().then(
() => {
res.status(201).json({
message: 'Post saved successfully!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
});
product.js
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
userId: { type: String, required: true },
inStock: { type: Boolean, required: true }
});
module.exports = mongoose.model('Product', productSchema);
[ad_2]