контактная форма работает на локальном хосте, но не на странице html - PullRequest
0 голосов
/ 02 мая 2020

Я использую node и express для отправки электронной почты через страницу html. Вот мое приложение:

`const express = require('express');
 const path = require('path');
 const nodeMailer = require('nodemailer');
 const bodyPaser = require('body-parser');

 const app = express()

 app.get('/', function (req, res) {
 res.sendFile(path.join(__dirname + '/index.html'));
 });


 app.set('view engine', 'html');
app.use(express.static('public'));
app.use(bodyPaser.urlencoded({ extended: true }));
app.use(bodyPaser.json());
var port = 3000;
app.get('/', function (req, res) {
res.render('index.html');
app.locals.layout = false;
});


 //internet connectivity check out
function checkInternet(cb) { 
require('dns').lookup('google.com', function (err) { 
    if (err && err.code == "ENOTFOUND") {
        cb(false);
    } else { 
        cb(true);
    }
})
}


app.post('/', (req, res) => {
const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>
<li>Name:${req.body.name}</li>
<li>Email:${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;

// create reusable transporter object using the default SMTP transport
let transporter = nodeMailer.createTransport({
    host: "mail.example.com",
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
        user: 'contact@example.com', // generated ethereal user
        pass: 'Y@$972200424' // generated ethereal password
    },
    tls: {
        rejectUnauthorized: false
    }
});

// send mail with defined transport object
let mailOptions = {
    from: `${req.body.email}`, // sender address
    to: "contact@example.com", // list of receivers
    subject: "Customer Message", // Subject line
    text: `SenderName: ${req.body.name}, --Message: ${req.body.message}`, // plain text body
    html: output // html body
};

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));

    if (info.messageId) {
        res.redirect('back');
     res.send(true);
    }
});
});


app.listen(3000, () => console.log('server is running at port 3000'));`

Дело в том, что оно отправляет электронную почту и прекрасно работает на localhost:3000, но то же самое НЕ работает на странице index.html. как я могу отправить письмо на страницу html?

1 Ответ

2 голосов
/ 02 мая 2020

Просто переместите html файлы в каталог publi c ниже. Вы должны изменить

app.use(express.static('public'));

на

app.use(express.static(`${__dirname}/public`));

и также изменить:

 app.get('/', function (req, res) {
 res.sendFile(path.join(__dirname + '/index.html'));
 });
* От 1009 * до
app.get('/', function (req, res) {
 res.sendFile(path.join(`${__dirname}/public/index.html`));
 });

Следуйте порядку строк:

app.use(express.static(`${__dirname}/public`));
app.get('/', function (req, res) {
  res.sendFile(path.join(`${__dirname}/public/index.html`));
});

Также вы можете использовать шаблон двигателя мопса. посмотрите это: c:

Использование шаблонизаторов с Express

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...