邮差请求不加载节点

时间:2018-04-06 11:27:56

标签: node.js mongodb

我是node.js的新手。试图从youtube

学习

几分钟前它完美地工作了。不确定发生了什么。命令没有错误。突然间它停在了邮递员处。

localhost:3000/orders完全正常显示消息message: 'Order was created',现在它无缘无故地停止工作。我无法调试,因为我无法看到任何错误。

no error

它就在这里。 enter image description here

这是orders.js路线。我收到的每个请求都有自定义消息。 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',
        order: 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;

app.js

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

const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders');

mongoose.connect('mongodb://**************@cssmania-shard-00-00-zfebp.mongodb.net:27017,cssmania-shard-00-01-zfebp.mongodb.net:27017,cssmania-shard-00-02-zfebp.mongodb.net:27017/test?ssl=true&replicaSet=cssmania-shard-0&authSource=admin');

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-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    if(req.method==='OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'GET,PUT, POST,PATCH,DELETE');
        return res.status(200).json({});
    }

})

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;

1 个答案:

答案 0 :(得分:3)

您应该在中间件中调用next(),以便请求可以继续。

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

您可以在Express Docs

中详细了解中间件