【问题标题】:Getting cannot get error on Postman for all my API's对于我的所有 API,在 Postman 上获取无法获取错误
【发布时间】:2020-09-18 15:19:41
【问题描述】:

我正在使用 nodejs、express 和 mongoose 开发一个后端项目。但是当我尝试在 Postman 上测试我的端点时,我不断收到这个错误。我是 nodejs 的新手,所以我不太确定这意味着什么。

这是我的主 js 文件 index.js

const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const apiRoute = require('./routes/api');
const adminRoute = require('./routes/admin');

mongoose.Promise = global.Promise;

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`listening to port ${port}`));
app.use(bodyParser.json());

app.use('/api', apiRoute);
app.use('/admin', adminRoute);

// As per Mongoose Documentation
const options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,

    autoIndex: false, // Don't build indexes
    //reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
    //reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    // If not connected, return errors immediately rather than waiting for reconnect
    bufferMaxEntries: 0,
    connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
    socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
    family: 4 // Use IPv4, skip trying IPv6
};

mongoose.connect('mongodb://localhost:27017/admin', options).then(
    () => {
        console.log('db connected');
    },
    (err) => {
        console.log('connection error');
    }
);

这是/routes/api.js

const router = express.Router();
const Ticket = require('../models/Ticket');
const Joi = require('joi');
const { seatValidation, typeValidation } = require('../validation');

//View all tickets
router.get('/tickets', async (req, res) => {
    try {
        let tickets = await Ticket.find();
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//View Ticket Status
router.get('/status/seat/:seat', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.params.seat);

    if (error) return res.status(404).send(error);

    try {
        let status = await Ticket.findOne({ seat: parseInt(req.params.seat) }).select('status');
        res.json(status);
    } catch (error) {
        res.json({ message: error });
    }
});

//View Details of person owning the ticket
router.get('/details/seat/:seat', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.params.seat);

    if (error) return res.status(404).send(error);

    try {
        let status = await Ticket.findOne({ seat: parseInt(req.params.seat) })
            .select('status')
            .select('first_name')
            .select('last_name')
            .select('gender')
            .select('email')
            .select('mobile');
        res.json(status);
    } catch (error) {
        res.json({ message: error });
    }
});

// adding empty seats
router.post('/add', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { error } = seatValidation(req.body);

    if (error) return res.status(404).send(error);

    let ticket = new Ticket({
        seat: req.body.seat,
        status: 'open'
    });

    let ticketSaved = await ticket.save();
    try {
        res.json(ticketSaved);
    } catch (error) {
        res.json({ message: error });
    }
});

//View all open tickets
router.get('/tickets/open', async (req, res) => {
    try {
        let tickets = await Ticket.find({ status: 'open' });
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//View all closed tickets
router.get('/tickets/closed', async (req, res) => {
    try {
        let tickets = await Ticket.find({ status: 'close' });
        res.json(tickets);
    } catch (error) {
        res.json({ message: error });
    }
});

//Update the ticket status (open/close + adding user details)
router.put('/status/:seat/:type', async (req, res) => {
    // input validation - seat should be a number and between 1-40
    let { seatError } = seatValidation(req.params.seat);

    if (seatError) return res.status(404).send(seatError);

    // input validation - type should be a string and should be 'open' or 'close'
    let { typeError } = typeValidation(req.params.type);

    if (typeError) return res.status(400).send(typeError);

    try {
        let type = req.params.type;
        if (type === 'open') {
            try {
                let ticket = await Ticket.updateOne(
                    { seat: req.params.seat },
                    {
                        $set: { status: 'open' },
                        $unset: { first_name: 1, last_name: 1, gender: 1, email: 1, mobile: 1 }
                    }
                );
                res.json(ticket);
            } catch (error) {
                res.json({ message: error });
            }
        } else if (type === 'close') {
            // input validation - type should be a string and should be 'open' or 'close'
            let ticketSchema = {
                first_name: Joi.string().min(3).required(),
                last_name: Joi.string().min(3).required(),
                gender: Joi.string().valid('M').valid('F').valid('U').required(),
                email: Joi.string().email().required(),
                mobile: Joi.number().integer().min(1000000000).max(9999999999).required()
            };

            let validation = Joi.validate(req.body, ticketSchema);

            if (validation.error) {
                res.status(400).send(validation.error);
                return;
            }

            try {
                let ticket = await Ticket.updateOne(
                    { seat: req.params.seat },
                    {
                        $set: {
                            status: 'close',
                            first_name: req.body.first_name,
                            last_name: req.body.last_name,
                            gender: req.body.gender,
                            email: req.body.email,
                            mobile: req.body.mobile
                        }
                    }
                );
                res.json(ticket);
            } catch (error) {
                res.json({ message: error });
            }
        }
    } catch (error) {
        res.json({ message: error });
    }
});

module.exports = router;

这是架构 /models/Ticket.js

const mongoose = require('mongoose');

const TicketSchema = mongoose.Schema({
    seat: Number,
    status: String,
    first_name: String,
    last_name: String,
    gender: String,
    email: String,
    mobile: Number
});

module.exports = mongoose.model('Ticket', TicketSchema);

谁能帮帮我?

这是邮递员的错误: Postman screenshot

【问题讨论】:

  • 你的节点服务器启动了吗?可以添加控制台的图片吗?
  • 你需要使用这个网址http://localhost:3000/api/tickets

标签: node.js express mongoose postman


【解决方案1】:

在您的 index.js 文件中,您已将 apiRoute 的路由指定为 /api,在屏幕截图中,您似乎错过了这一点。 请使用网址为localhost:3000/api/tickets 而不仅仅是localhost:3000/tickets,它应该可以正常工作。 如您所见,您错过了/api 部分,express 没有您请求的路径,并返回 404 not found 的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2020-12-11
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2022-01-04
    • 2016-07-10
    相关资源
    最近更新 更多