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

jay*_*ipt 4 javascript xmlhttprequest node.js express

我正在尝试制作一个获取电子邮件地址并发送回复邮件的表单.我在vanilla 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
  }
});
Run Code Online (Sandbox Code Playgroud)
<!-- 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>
Run Code Online (Sandbox Code Playgroud)

Yan*_* Li 9

在此之前可以做一些事情

  • 决定是否要使用GET或POST,您似乎对使用哪一个感到困惑.我会使用POST,因为你试图发送电子邮件的数据,而不是真的试图从服务器获取数据.
  • 更改你的app.post节点功能(假设你想发帖)
  • 您需要将一个字符串发送到服务器,因此json stringify
  • 由于您的字符串是json格式,您需要将标题"Content-Type"更改为"application/json"
  • 您需要将请求动词更改为"POST"以匹配您的服务器以及您要完成的任务

在您的服务器中,您需要替换app.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
  }
});
Run Code Online (Sandbox Code Playgroud)

这应该在客户端上做到了

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));
Run Code Online (Sandbox Code Playgroud)

XMLHttpRequest的替代解决方案

或者,您可以通过HTTP api- axios查看此库中的糖

如果你正在使用axios,那就简单了

data = {to: to, subject: subject, text: text};
axios.post('/user', data);
Run Code Online (Sandbox Code Playgroud)

或者如果你想控制收到回复时会发生什么.

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