Как устранить неполадки «не могу опубликовать» в node.js - PullRequest
0 голосов
/ 08 января 2019

У меня проблемы с простым приложением узлов, использующим Node, Mongo, Express и Edge для представлений.

Когда я пытаюсь предоставить данные через форму в представлениях, я получаю следующее сообщение.

«Невозможно POST / тире / дата / создать»

У меня такое ощущение, что это как-то связано с неосторожной ошибкой, которую я не могу точно определить, поскольку я делал это в предыдущих проектах без проблем. Я оглянулся на эти проекты и до сих пор не могу понять, где я ошибся. Кто-то здесь, вероятно, сможет найти его в кратчайшие сроки.

date_create.edge (вид)

    <!--title-->
    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" placeholder="Title" id="title" name="title" required="true" class="form-control" value=""/>
    </div>
    <br>
    <!--class-->
    <div class="form-group">
        <label for="class">Class</label>
        <input type="text" placeholder="Class" id="class" name="class" required="true" class="form-control" value=""/>
    </div>
    <br>
    <!--description-->
    <div class="form-group">
        <label for="description">Description</label>
        <textarea type="text" placeholder="Description" id="description" name="description" required="true" class="form-control" value=""></textarea>
    </div>
    <br>
    <!--date-->
    <div class="form-group">
        <label for="date">Date</label>
        <input type="number" placeholder="Date" id="date" name="date" required="true" class="form-control" value=""/>
    </div>
    <br>
    <!--day-->
    <div class="form-group">
        <label for="day">Day</label>
        <input type="text" placeholder="Day" id="day" name="day" required="true" class="form-control" value=""/>
    </div>
    <br>
    <!--month-->
    <div class="form-group">
        <label for="month">Month</label>
        <input type="text" placeholder="Month" id="month" name="month" required="true" class="form-control" value=""/>
    </div>
    <br>
    <!--time-->
    <div class="form-group">
        <label for="time">Time</label>
        <input type="text" placeholder="Time" id="time" name="time" required="true" class="form-control" value=""/>
    </div>
    <br>
<br>
<button type="submit">Submit</button>

Date.js (модель)

const mongoose = require('mongoose');

const DateSchema = new mongoose.Schema({
    title: String,
    class: String,
    description: String,
    date: Number,
    day: String,
    month: String,
    time: String
});

const Date = mongoose.model('Date', DateSchema);

module.exports = Date

routes.js

//--REQUIREMENTS--\\
const express = require('express');
const router = express.Router();



//--CONTROLLERS--\\
const article_controller = require('../Controllers/article_controller');
const class_controller = require('../Controllers/class_controller');
const dash_controller = require('../Controllers/dash_controller');
const date_controller = require('../Controllers/date_controller');



//--DASHBOARD--\\
router.get('/', dash_controller.index);



//--DATE--\\
// GET request for creating a Date
router.get('/date/create', date_controller.date_create_get);

// POST request for creating a Date
router.post('date/create', date_controller.date_create_post);

* * date_controller.js тысячи двадцать-шести * * тысяча двадцать семь (контроллер) * 1 028 *

const { body,validationResult } = require('express-validator/check');
const { sanitizeBody } = require('express-validator/filter');
const Date = require('../Models/Date');

const async = require('async');

//--DATE--\\
// GET request for creating a Date
exports.date_create_get = function(req, res){
    res.render('date_create')
}

// POST request for creating a Date
exports.date_create_post = [

    //Validate Fields
    body('title').isLength({ min: 1 }).trim().withMessage('Title must be specified.'),
    body('class').isLength({ min: 1 }).trim().withMessage('Class must be specified.'),
    body('description').isLength({ min: 1 }).trim().withMessage('Description must be specified.'),
    body('date').isLength({ min: 1 }).trim().withMessage('Date must be specified.'),
    body('day').isLength({ min: 1 }).trim().withMessage('Day must be specified.'),
    body('month').isLength({ min: 1 }).trim().withMessage('Month must be specified.'),
    body('time').isLength({ min: 1 }).trim().withMessage('Time must be specified.'),

    //Sanitize Fields
    sanitizeBody('title').trim().escape(),
    sanitizeBody('class').trim().escape(),
    sanitizeBody('description').trim().escape(),
    sanitizeBody('date').trim().escape(),
    sanitizeBody('day').trim().escape(),
    sanitizeBody('month').trim().escape(),
    sanitizeBody('time').trim().escape(),

    //Process request after validation and sanitation.
    (req, res, next) => {
        //Extract the validation errors from a request.
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            // There are errors. Render form again with sanitized values/errors messages.
            res.render('date_create', { title: 'Create Date', date: req.body, errors: errors.array() });
            return;
        }
        else {
            //Data form form is valid

            // Create Date object with escaped and trimmed data.
            // title, class, description, date, day, month, time
            var date = new Date(
                {
                    title: req.body.title,
                    class: req.body.class,
                    description: req.body.description,
                    date: req.body.date,
                    day: req.body.day,
                    month: req.body.month,
                    time: req.body.time
                });
            date.save(function (err) {
                if (err) {return next(err);}
                //Successful - redirect
                res.redirect('date_list');
            });
        }
    }
];

Как я уже сказал, здесь, вероятно, просто неосторожная ошибка. Я использовал console.log почти везде, где только мог придумать, и приложение не отвечает в контрольном файле. Это приводит меня к мысли, что форма (представление) - это проблема.

Ответы [ 2 ]

0 голосов
/ 08 января 2019

Ваш почтовый запрос в порядке, попробуйте это:

    var router = require('express')();

    router.post('/date/create', function(req, res, next) {
      // Your code here
      //Validate Fields
    body('title').isLength({ min: 1 }).trim().withMessage('Title must be specified.'),
    body('class').isLength({ min: 1 }).trim().withMessage('Class must be specified.'),
    body('description').isLength({ min: 1 }).trim().withMessage('Description must be specified.'),
    body('date').isLength({ min: 1 }).trim().withMessage('Date must be specified.'),
    body('day').isLength({ min: 1 }).trim().withMessage('Day must be specified.'),
    body('month').isLength({ min: 1 }).trim().withMessage('Month must be specified.'),
    body('time').isLength({ min: 1 }).trim().withMessage('Time must be specified.'),

    //Sanitize Fields
    sanitizeBody('title').trim().escape(),
    sanitizeBody('class').trim().escape(),
    sanitizeBody('description').trim().escape(),
    sanitizeBody('date').trim().escape(),
    sanitizeBody('day').trim().escape(),
    sanitizeBody('month').trim().escape(),
    sanitizeBody('time').trim().escape(),

   //Extract the validation errors from a request.
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            // There are errors. Render form again with sanitized values/errors messages.
            res.render('date_create', { title: 'Create Date', date: req.body, errors: errors.array() });
            return;
        }
        else {
            //Data form form is valid

            // Create Date object with escaped and trimmed data.
            // title, class, description, date, day, month, time
            var date = new Date(
                {
                    title: req.body.title,
                    class: req.body.class,
                    description: req.body.description,
                    date: req.body.date,
                    day: req.body.day,
                    month: req.body.month,
                    time: req.body.time
                });
            date.save(function (err) {
                if (err) {return next(err);}
                //Successful - redirect
                res.redirect('date_list');
            });
        }

    });

Это также должно работать:

router.post('/date/create', date_controller.date_create_post);
0 голосов
/ 08 января 2019

Я думаю, что вы забыли добавить косую черту перед 'date' в URL-адресе в методе post в файле route.js.

Как это

router.post('/date/create', date_controller.date_create_post);
...