Internal Error 500 at POST request Express JS and Formidable

。_饼干妹妹 提交于 2020-01-06 06:54:16

问题


I want to send form data (multipart) to my express js server. I learned I could use multer or formidable. Formidable seemed easy to understand for me So I went with it, but I am having issue I need guidance with. I keep getting this error 500 internal server and I just can't figure out what am I doing wrong.

Here is my app.js

'use strict';
var debug = require('debug');
var express = require('express');
var fs = require('fs');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars')
var mongoose = require('mongoose');
var session = require('express-session');
var moment = require('moment');
var helpers = require('handlebars-helpers')();
var formidableMiddleware = require('express-formidable');
var multer = require('multer');
//var storage = multer.diskStorage({
//    destination: 'uploads/',
//    filename: function (req, file, callback) {
//        callback(null, file.filename + '-' + path.extname(file.originalname));

//    }


//});

//var upload = multer({ storage: storage }).single('img_');

var db = require('./dbconn');


db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('we are connected!');
});


var index = require('./routes/index');
var users = require('./routes/users');
var signup = require('./routes/signup');
var login = require('./routes/login');
var adreqform = require('./routes/adreqform');
var dashboard = require('./routes/dashboard');
var logout = require('./routes/logout');
var posts = require('./routes/posts');
var managereq = require('./routes/managereq');
var admindash = require('./routes/admindash');
var profile = require('./routes/profile');


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('hbs', exphbs({ extname: '.hbs', defaultLayout: 'layout' }));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'gh jewellery',
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false }


}));


app.use(function (req, res, next) {
    console.log('middleware was called');
    res.locals.session = req.session;
    req.session.LoggedIn = false;

    next();
}); 


app.use('/', index);
app.use('/users', users);
app.use('/dashboard', dashboard);
app.use('/signup', signup);
app.use('/login', login);
app.use('/adreqform', adreqform);
app.use('/logout', logout);
app.use('/posts', posts);
app.use('/managereq', managereq);
app.use('/admindash', admindash);
app.use('/profile', profile);


app.use(formidableMiddleware({
    encoding: 'utf-8',
    uploadDir: 'C:/Users/mesam/Desktop/',
    multiples: true,
    keepExtensions: true,
    hash: false
}));



// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

app.set('port', process.env.PORT || 3000);

module.exports = app;

var server = app.listen(app.get('port'), function () {
    debug('Express server listening on port ' + server.address().port);


});

and here is my users.js a route code file where the post route is written that will be receiving the form data.

'use strict';
var express = require('express');
var router = express.Router();
var User = require('../models/user.model.js');

/* GET users listing. */
router.get('/allnotifications', function (req, res) {
    res.render('allnotifications');
});

router.post('/upload', function (req, res) {

    console.log("This is somevar req.fields.heading " + req.fields.heading);
    console.log("This is someanothervar req.fields.heading " + req.fields.heading);
    console.log("This is someanothervar req.fields.heading " + req.body.heading);
    console.log("req.files[0]" + req.files);


});

module.exports = router;

and here is the HTML code for the form

form.hbs

<form action="/users/upload" method="POST" enctype="multipart/form-data">

    <div class="container">

        <h1 class="text-center">Post Ad to seller community</h1><br>

        <fieldset class="form-group">

            <ul class="list-group">

                <li class="list-group-item">
                    <small><a href="/files" style="text-decoration: underline; float:right;">How to write an effective Ad</a></small>
                    <h6>Describe your post</h6><br>

                    <div class="row">
                        <div class="col-12">
                            <div class="form-group row">
                                <h4 class="col-sm-2 col-form-label"><i class="fas fa-edit fa-lg"></i> Title</h4>
                                <div class="col-sm-10">
                                    <input id="heading" name="heading" type="text" class="form-control" placeholder="Post heading" maxlength="40">
                                    <small id="passwordHelpInline" class="text-muted" style="font-size: 11px; font-style: italic;">
                                        *Required
                                    </small>
                                    <small id="charcounterheading" class="text-muted" style="font-size: 12px; float:right;">
                                        40 characters remaining
                                    </small>
                                </div>
                            </div>
                        </div>


                        <div class="col-12">
                            <div class="form-group row">
                                <h4 class="col-form-label col-sm-2 pt-0"><i class="far fa-sticky-note fa-lg"></i> Description</h4>
                                <div class="col-sm-10">
                                    <textarea id="opdesc" name="opdesc" class="form-control" rows="4" placeholder="Additional description about your order." maxlength="300"></textarea>
                                    <small class="text-muted" style="font-size: 11px; font-style: italic;">
                                        *Required
                                    </small>
                                    <small id="charcounterdesc" class="text-muted" style="font-size: 12px; float:right;">
                                        300 characters remaining
                                    </small>
                                </div>

                            </div>

                        </div>





                    </div>

                </li>
                <li class="list-group-item">

                    <h6>Specifications of your order</h6><br>
                    <div class="form-group row">
                        <h4 class="col-sm-2 col-form-label"><i class="fas fa-weight fa-lg"></i> Weight</h4>
                        <div class="col-sm-6">
                            <div class="input-group-append">

                                <input name="weight" type="number" id="weight" class="form-control" placeholder="Weight" step="0.01">

                                <select class="form-control" id="unit" name="unit">
                                    <option class="text-muted" value="grams" name="unit">gram(s)</option>
                                    <option class="text-muted" value="kilos" name="unit">kilo(s)</option>
                                    <option class="text-muted" value="tons" name="unit">ton(s)</option>
                                </select>

                            </div>
                            <small class="text-muted" style="font-size: 11px; font-style: italic;">
                                *Required
                            </small>
                        </div>

                    </div>

                    <div class="row">

                        <h4 class="col-form-label col-sm-2 pt-0"><i class="fab fa-creative-commons-remix fa-lg"></i> Metal</h4>
                        <div class="col-sm-10">
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="metal" id="24kradio" value="24 Carat" checked>
                                <label class="form-check-label" for="24kradio">
                                    24 Carat
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="metal" id="22kradio" value="22 Carat">
                                <label class="form-check-label" for="22kradio">
                                    22 Carat
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="metal" id="21kradio" value="21 Carat">
                                <label class="form-check-label" for="21kradio">
                                    21 Carat
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="metal" id="18kradio" value="18 Carat">
                                <label class="form-check-label" for="18kradio">
                                    18 Carat
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="metal" id="925radio" value="925 Silver">
                                <label class="form-check-label" for="925radio">
                                    925 Silver
                                </label>
                            </div>
                            <small class="text-muted" style="font-size: 11px; font-style: italic;">
                                *Optional
                            </small>
                        </div>
                    </div>
                </li>
                <li class="list-group-item">
                    <h6>When would you like your order to be delivered by?</h6><br>

                    <div class="form-group row">
                        <h4 class="col-sm-2 col-form-label"><i class="far fa-clock fa-lg"></i> Date</h4>
                        <div class="col-sm-4">
                            <input name="date" type="date" id="date" class="form-control">
                            <small class="text-muted" style="font-size: 11px; font-style: italic;">
                                *Optional
                            </small>
                        </div>

                    </div>


                </li>

                <li class="list-group-item">
                    <h6>Attach sample images </h6><br>

                    <div class="form-group">

                        <input type="file" name="upload" multiple>


                    </div>


                </li>
                <li class="list-group-item">

                    <!--<button type="submit" value="submit" class="btn btn-light float-right"> Submit </button>-->

                    <input type="submit" value="Submit">

                </li>
            </ul>



        </fieldset>



    </div>


</form>

Error shown through the Chrome Developer's tool Network Tab

Request URL: http://localhost:3000/users/upload
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Length: 9064
Content-Type: text/html; charset=utf-8
Date: Fri, 05 Apr 2019 14:49:03 GMT
ETag: W/"2368-a3XoEWk9NKlQ1Y8deafZFGHI/9I"
X-Powered-By: Express
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cache-Control: max-age=0
Connection: keep-alive
Content-Length: 1058872
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryLDlAJKC5C4X1sTVJ
Cookie: amplitude_id_7acb8df1d57962e98163686ab410fa23_crystal_ce_amplitude=eyJkZXZpY2VJZCI6ImZlYTNlMTU4LWY3N2ItNDU1NS1iNzJiLWE4NzNlNWQyOTA3YlIiLCJ1c2VySWQiOm51bGwsIm9wdE91dCI6ZmFsc2UsInNlc3Npb25JZCI6MTU0MTA1NjcyNjk5MSwibGFzdEV2ZW50VGltZSI6MTU0MTA1OTgxODUzNCwiZXZlbnRJZCI6MCwiaWRlbnRpZnlJZCI6MCwic2VxdWVuY2VOdW1iZXIiOjB9; connect.sid=s%3A7ijTBhOdaVMypL_hQPnCpl0wMN25ivSo.5PifUk6JlJwK9SoPq7gETaC4ggZ1xCR9AyR5JAwiY34
Host: localhost:3000
Origin: http://localhost:3000
Referer: http://localhost:3000/adreqform
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36

Error show the the CMD for server side

POST /users/upload 500 37.709 ms - 9064
GET /stylesheets/main.css 304 2.152 ms - -

Thanks a lot for the help/guidance

来源:https://stackoverflow.com/questions/55537877/internal-error-500-at-post-request-express-js-and-formidable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!