0

我一直在谷歌搜索,在堆栈上搜索并试图解决这个问题有一段时间了。发布的解决方案似乎都没有帮助。

服务器在 VSC 中运行顺利(如果我输入错误的 pass,它会给出身份验证错误。看起来,它连接正常)。用 Compass 试过,它在那里也连接得很好。

在 Postman [RAW > JSON/Application] 中发布此内容:

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

在 VSC 中返回:

POST /products - - ms - -

Postman 中出现错误消息:Error: read ECONNRESET

我在 youtube 上关注 RESTful API 系列。 我对问题出在哪里有点困惑。有任何想法吗?

任何帮助将不胜感激。提前致谢!

服务器.js

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

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

const server = http.createServer(app);

server.listen(port);

应用程序.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;

模型/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);

路线/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;

路线/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>"
    }
}
4

0 回答 0