A few things before this can work.
- Decide whether you want to use GET or POST, you seem to be confused as to which one to use. I would use POST because you are trying to send data for email and not trying to receive data from the server.
- Change the app.post node function (if you want to send a message)
- You need to send a string to the server, so json stringify
- Since your string is in json format, you need to change the "Content-Type" header to "application / json"
- You need to change your request verb to "POST" so that it matches your server and what you are trying to execute
On your server you need to replace the app.post code (you need to install npm to 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 } });
This should do the trick on the client
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));
Alternative Solution for XMLHttpRequest
Alternatively you can look at this sugar library via HTTP api - axios
If you use axioms, it is as simple as
data = {to: to, subject: subject, text: text}; axios.post('/user', data);
or if you want to control what happens when you get a response.
data = {to: to, subject: subject, text: text}; axios.post('/user', data) .then(function (response) { console.log('success'); }) .catch(function (response) { console.log('error'); });