我正在尝试制作一个表单,它会接收电子邮件地址并发回交易电子邮件。我在香草JavaScript中使用XMLHttpRequest将数据发送到服务器,但是当我查看从index.html发送的数据时,它只是服务器端的空对象。为什么发送到Node/Express服务器的XMLHttpRequest中的对象为空?
在后端我使用Node和Express和Nodemailer。 Nodemailer工作正常。我一直试图弄清楚为什么查询对象中没有任何东西。
// Here is server.js
var express = require('express');
var nodemailer = require('nodemailer');
var app = express();
// Send index.html
app.get('/', function(request, response) {
response.sendfile('index.html');
});
// Where I should receive data from JS written in index.html
app.post('/send', function(req, res) {
var mailOptions = {
to: req.query.to,
subject: req.query.subject,
text: req.query.text
}
});
<!-- Here is my index.html with some JS in it -->
<div>
<input id="to" type="text" placeholder="Email" />
<input id="subject" type="text" placeholder="subject" />
<textarea id="content" cols="20" rows="2" placeholder="Write something"></textarea>
<button id="submit">Submit</button>
</div>
<script>
// When #submit is clicked it invokes a function to collect values and then makes a XMLHttpRequest like bellow
data = {to: to, subject: subject, text: text};
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:3000/send', true);
request.send(data);
}
</script>
你的XMLHttpRequest发送“GET”请求,但您的Express服务器期待一个“POST”请求 –
@PHPglue他竖起代码是他的实际代码片段,因此它为什么未定义 –
没有与'发.send()'使用'GET',只使用'.open()'URL。如果你想使用'POST'发送数据或者将数据追加到URL如:'?to = val1&subject = val2&text = val3'。要么或使用jQuery,那么你可以传递数据对象。 – PHPglue