联系表单帖子并重定向无法正常工作

时间:2018-02-20 16:23:02

标签: node.js forms

最终修改

搞定了

将路线更改为

close

原始问题

我正在尝试创建联系表单,但我收到以下错误:

image

这是我到目前为止的代码:

index.js

res.render('contact/thankyou', {
  pageTitle: 'Rafflefly | Thank You'
});

contacts_controller.js

/* contact ROUTES. */
router.get('/contact', contacts_controller.contact_index);
router.post('/contact/send', contacts_controller.send_contact);

文件结构

image #2

据我所知,一切都设置正确,但显然这里缺少了一些东西。

*编辑#1 **

这是app.js文件,这是使用快速生成器生成的应用程序。

app.js

var nodemailer = require('nodemailer');

exports.contact_index = function(req, res, next) {
  res.render('contact/contact', { title: 'Rafflefly | Contact' });
}

exports.send_contact = function(req, res, next) {
  const output = `
    <p>You have a new contact request from ${req.body.first_name} ${req.body.last_name} saying the following message:</p>
    <p>${req.body.message}</p>
  `;

  nodemailer.createTestAccount((err, account) => {
    // create reusable transporter object using the default SMTP transport
    if (process.env.NODE_ENV === 'production') {
      transporter = nodemailer.createTransport({
        host: "smtp.sendgrid.net",
        port: 587,
        auth: {
          user: process.env.SENDGRID_USERNAME,
          pass: process.env.SENDGRID_PASSWORD,
        }
      });
    } else {
      transporter = nodemailer.createTransport({
        host: "smtp.ethereal.email",
        port: 587,
        auth: {
          user: 'qkkvnabtziufbksa@ethereal.email',
          pass: 'A4W9HF2WbhAav263VM',
        }
      });
    }
    // setup email data with unicode symbols
    let mailOptions = {
      from: process.env.GLOBAL_EMAIL || 'ben@benbagley.co.uk', // sender address
      to: `${req.body.email}`, // list of receivers
      subject: 'New contact request', // Subject line
      text: output
    };
    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        return console.log(error);
      }

      console.log('Message sent: %s', info.messageId);
      console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

      // req.flash('success_msg', 'Your email has been sent!');
      res.redirect('thankyou', { title: 'Rafflefly | Thank You' });
    });
  });
}

编辑#2

我的表单正常var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var sassMiddleware = require('node-sass-middleware'); var nodemailer = require('nodemailer'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); const port = process.env.PORT || 3000; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(sassMiddleware({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public'), indentedSyntax: true, // true = .sass and false = .scss sourceMap: true })); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); // 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 handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;

我还将重定向更改为此

form(class='w-full max-w-md m-auto p-8' action='/contact/send' method='POST')

但现在网址呈现 // req.flash('success_msg', 'Your email has been sent!'); res.redirect(301, '/contact/thankyou', { title: 'Rafflefly | Thank You' }) 而不是http://localhost:3000/contact/301

1 个答案:

答案 0 :(得分:0)

查看问题编辑和答案的最终编辑。