0

I have been googling, searching on stack and been trying to solve this for a while now. None of the posted solutions seem to help.

Server runs smoothly in VSC (if I input wrong pass, it gives authentication error. Seemingly, it connects fine). Tried with Compass and it connects fine there too.

Posting this in Postman [RAW > JSON/Application]:

{
    "name": "Harry Potter",
    "price": "12.99"
}

Returns this in VSC:

POST /products - - ms - -

And an error message in Postman: Error: read ECONNRESET

I am following a RESTful API series on youtube. I am a bit confused as to where the problem lies then. Any ideas?

Any help would be greatly appreciated. Thanks in advance!

server.js

const http = require('http');
const app = require('./app');

const port = process.env.PORT || 3000;

const server = http.createServer(app);

server.listen(port);

app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

// Set route for product and order
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders');

mongoose.connect(
    'mongodb://testDB:' + 
        process.env.MONGO_ATLAS_PW + 
        '@node-rest-shop-shard-00-00.e0tzo.mongodb.net:27017,node-rest-shop-shard-00-01.e0tzo.mongodb.net:27017,node-rest-shop-shard-00-02.e0tzo.mongodb.net:27017/test?ssl=true&replicaSet=atlas-be641c-shard-0&authSource=admin&retryWrites=true&w=majority', 
    {
        useNewUrlParser: true,
        useUnifiedTopology: true
    }
);

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Header', 'Origin, X-Requested-Width, Content-Type, Accept, Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
        return res.status(200).json({});
    }
});

// Routes which handles 
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);

app.use((req, res, next) => {
    const error = new Error('Not found');
    error.status = 404;
    next(error);
})

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
       error: {
           message: error.message
       } 
    });
});

module.exports = app;

models/product.js

const mongoose = require('mongoose');

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectID,
    name: String,
    price: Number
});

module.exports = mongoose.model('Product', productSchema);

routes/orders.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) => {
    res.status(200).json({
        message: 'Orders were fetched'
    });
});

router.post('/', (req, res, next) => {
    const order = {
        productId: req.body.productId,
        quantity: req.body.quantity
    };
    res.status(201).json({
        message: 'Order was created',
        orders: order
    });
});


router.get('/:orderId', (req, res, next) => {
    res.status(200).json({
        message: 'Order details',
        orderId: req.params.orderId
    });
});

router.delete('/:orderId', (req, res, next) => {
    res.status(200).json({
        message: 'Order deleted',
        orderId: req.params.orderId
    });
});

module.exports = router;

routes/products.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');

const Product = require('../models/product');

router.get('/', (req, res, next) => {
    res.status(200).json({
        message: 'handling GET requests to /products'
    });
});

router.post('/', (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price
    });
    product.save().then(result => {
        console.log(result);
    })
    .catch(err => console.log(err));
    res.status(201).json({
        message: 'handling POST requests to /products',
        createProduct: product
    });
});

router.get('/:productId', (req, res, next) => {
    const id = req.params.productId;
    if (id === 'special') {
        res.status(200).json({
            mesage: 'Special ID discovered',
            id: id
        });
    } else {
        res.status(200).json({
            message: 'You passed an ID',
            id: id
        });
    }
});

router.patch('/:productId', (req, res, next) => {
    res.status(200).json({
       message: 'Updated product!' 
    });
});

router.delete('/:productId', (req, res, next) => {
    res.status(200).json({
       message: 'Deleted product!' 
    });
});

module.exports = router;

nodemon.json

{
    "env": {
        "MONGO_ATLAS_PW": "<user password here - removed for post>"
    }
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
CodeMonkey
  • 11
  • 5
  • Did you check your terminal for the errors? – Niraj Patel Nov 13 '20 at 11:30
  • Terminal in VSC? I am not getting any errors in return there. Only in postman. Postman console: `POST http://localhost:5000/products Error: read ECONNRESET Request Headers Content-Type: application/json User-Agent: PostmanRuntime/7.26.8 Accept: */* Cache-Control: no-cache Postman-Token: ac13eaad-8843-4c23-9847-fd76c4224fed Host: localhost:5000 Accept-Encoding: gzip, deflate, br Connection: keep-alive` – CodeMonkey Nov 13 '20 at 12:16
  • I don't think there should be anything postman specific, postman is just a client which helps you to communicate with your backend server. Also you do need to explicitly set ```_id``` , mongodb will handle it. – Niraj Patel Nov 13 '20 at 12:19
  • Yeah. It's just not returning anything when called which is why I'm confused. Where do you mean the id needs to be set to _id? In the error blocks? – CodeMonkey Nov 13 '20 at 13:17
  • In ```routes/product.js``` , ```/``` post request, where you are adding a new product, you just need to add name and price, _id will be added by mongo. – Niraj Patel Nov 13 '20 at 13:20
  • I see! Doesn't seem to make any difference – CodeMonkey Nov 13 '20 at 13:38

0 Answers0