为什么发送给Node / Express服务器的XMLHttpRequest对象是空的?

我正在尝试制作一个表单,它会接收电子邮件地址并发送交易电子邮件。 我在香草JavaScript中使用XMLHttpRequest发送数据到服务器,但是当我查看从index.html发送的数据时,它只是服务器端的一个空对象。

在后端我使用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> 

在这之前有一些事情可以工作

  • 决定是否要使用GET或POST,您似乎对使用哪一个感到困惑。 我会使用POST,因为您正在尝试为电子邮件发送数据,而不是真的试图从服务器获取数据。
  • 改变你的app.post节点的function(假设你想发布)
  • 你需要发送一个string到服务器,因此json stringify
  • 由于你的string是json格式,所以你需要把头文件“Content-Type”改为“application / json”
  • 您需要将您的请求动词更改为“POST”以匹配您的服务器以及您正在尝试完成的内容

在你的服务器上,你需要replaceapp.post代码(你需要npm install body-parser)

 var bodyParser = require('body-parser'); app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded // Where I should receive data from JS written in index.html app.post('/send', function(req, res) { var mailOptions =  { to: req.body.to, subject: req.body.subject, text: req.body.text } }); 

这应该在客户端做的伎俩

 data = {to: to, subject: subject, text: text}; var request = new XMLHttpRequest(); request.open('POST', 'http://localhost:3000/send', true); xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); request.send(JSON.stringify(data)); 

XMLHttpRequest的替代解决scheme

另外,你也可以通过HTTP api – axios来查看这个库

如果你使用的是axios,就像

 data = {to: to, subject: subject, text: text}; axios.post('/user', data); 

或者如果您想要控制收到答复时发生的情况。

 data = {to: to, subject: subject, text: text}; axios.post('/user', data) .then(function (response) { console.log('success'); }) .catch(function (response) { console.log('error'); });