i am coding backend for my expense tracker app.
when i click on Submit button, in the network tab, the above error is displayed.
here is the code:
index.js
const express = require('express')
const app = express();
const cors = require('cors');
const Transaction = require('./models/Transaction.js')
const mongoose = require("mongoose");
require('dotenv').config();
app.use(cors());
app.use(express.json());
app.get('/api/test', (req, res) => {
res.json('test ok')
})
app.post('/api/transaction',async (req, res) => {
await mongoose.connect(process.env.MONGO_URL);
console.log(process.env.MONGO_URL)
const { name, description, amount } = req.body;
const transaction = await Transaction.create({name,description,amount})//Transaction -> model.schema of DB
res.json(transaction);
})
app.listen(4000, () => {
console.log('server is running on port 4000')
})
the data i am trying to send is not displaying in the mongodb
2
Answers
Have you looked at req.body and then at the values that got loaded into name, description, amount from the body?
IF those values don’t look right, then what about on the front end, what does the data look like that is being sent to the server?
Comments and suggestions:
Please enclose the following statement in a try-catch error handling block as the async database function invocation has been evaluated with await keyword. Additionally in case you are using Express 4+, then the error if any in a async handler must be passed on to Express. Please see below for the code enhanced on these lines.
Code enhanced
From Express 4.16.0 onwards, express.json is a built-in middleware, therefore there is no need to load it as below.