简体   繁体   English

使用 vanilla JS ajax 发送数据并使用 Node api 读取数据

[英]Sending data with vanilla JS ajax and reading it with Node api

I have this code on my client side:我的客户端有这个代码:

sendMail(e) {
    e.preventDefault();
    var name = document.getElementById('name').value;
    var contactReason = document.getElementById('contactReason').value;
    var email = document.getElementById('email').value;
    var additionalInfo = document.getElementById('additionalInfo').value;
    var body = {
        name: name,
        contactReason: contactReason,
        email: email,
        additionalInfo: additionalInfo,
    };
    console.log(body);
    fetch('http://localhost:4000/', {
        method: 'POST',
        body: body.toString(),
    }).then(r => console.log(r)).catch(e => console.log(e));
}

And this kind of works.而这种作品。 It logs the object to the console, and sends something to the back end.它将对象记录到控制台,并向后端发送一些内容。

Here's my Node call:这是我的节点调用:

var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());

var a = '=';
router.post('/', (req, res, next) => {
        console.log('mailing');
        console.log(a);
        console.log(req.body);
        a += '=';
        var nodemailer = require('nodemailer');

        var transporter = nodemailer.createTransport({
            host: "smtp.gmail.com", // hostname
            auth: {
                user: '******',
                pass: '******'
            }
        });

        let mailOptions = {
            from: `${req.body.name} ${req.body.email}`, // sender address
            to: 'alexander.ironside@mygeorgian.ca', // list of receivers
            subject: 'Email from UczSieApp contact form', // Subject line
            text: 'Hello world ', // plaintext body
            html: `
                        <h4>Imie: ${req.body.name}</h4>
                        <h4>Email: ${req.body.email}</h4>
                        <h4>Powod kontaktu: ${req.body.contactReason}</h4>
                        <p>Wiadomosc: ${req.body.additionalInfo}</p>
                        `
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });
    }
);
module.exports = router;

So what the code does right now:那么代码现在做了什么:

The object is being created, something (not sure what exactly) is being send to Node back-end, and an email is being sent.正在创建对象,一些东西(不确定到底是什么)正在发送到 Node 后端,并且正在发送一封电子邮件。 But req.body is logged as {} .但是req.body被记录为{}

What I want to do:我想做的事:

Read the values sent to the back-end as body and send an email with this data.将发送到后端的值作为body读取,并发送包含此数据的电子邮件。

What am I missing?我错过了什么?

I used GET instead of POST and this solved my problems.我使用 GET 而不是 POST 这解决了我的问题。 It is kind of a cheat but it works.这是一种作弊,但它有效。

should add to fetch应该添加到获取

            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },

            body: JSON.stringify(body),

all correct code所有正确的代码

frontend前端

sendMail(e) {
    e.preventDefault();
    var name = document.getElementById('name').value;
    var contactReason = document.getElementById('contactReason').value;
    var email = document.getElementById('email').value;
    var additionalInfo = document.getElementById('additionalInfo').value;
    var body = {
        name: name,
        contactReason: contactReason,
        email: email,
        additionalInfo: additionalInfo,
    };
    console.log(body);
    fetch('http://localhost:4000/', {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },

        body: JSON.stringify(body),
        method: 'POST',
    }).then(r => console.log(r)).catch(e => console.log(e));
}

backend后端

var express = require('express');
var router = express.Router();
var cors = require('cors');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.options('*', cors());

var a = '=';
router.post('/', (req, res, next) => {
        console.log('mailing');
        console.log(a);
        console.log(req.body);
        a += '=';
        var nodemailer = require('nodemailer');

        var transporter = nodemailer.createTransport({
            host: "smtp.gmail.com", // hostname
            auth: {
                user: '******',
                pass: '******'
            }
        });

        let mailOptions = {
            from: `${req.body.name} ${req.body.email}`, // sender address
            to: 'alexander.ironside@mygeorgian.ca', // list of receivers
            subject: 'Email from UczSieApp contact form', // Subject line
            text: 'Hello world ', // plaintext body
            html: `
                        <h4>Imie: ${req.body.name}</h4>
                        <h4>Email: ${req.body.email}</h4>
                        <h4>Powod kontaktu: ${req.body.contactReason}</h4>
                        <p>Wiadomosc: ${req.body.additionalInfo}</p>
                        `
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                return console.log(error);
            }

            console.log('Message sent: ' + info.response);
        });
    }
);
module.exports = router;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM