我正在嘗試製作一個表單,它會接收電子郵件地址併發回交易電子郵件。我在香草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