skip to Main Content

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


  1. 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?

    Login or Signup to reply.
  2. 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.

    const transaction = await Transaction.create({name,description,amount})
    res.json(transaction);
    

    Code enhanced

    try {
        const transaction = await Transaction.create({name,description,amount});
        res.json(transaction);
      
    } catch(error) {
       next(error)
    }
    

    From Express 4.16.0 onwards, express.json is a built-in middleware, therefore there is no need to load it as below.

    app.use(express.json());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search