【发布时间】:2018-11-30 20:25:00
【问题描述】:
我正在尝试使用 React 向 Node 发送一些数据。这是我的反应代码:
sendMail(e) {
e.preventDefault();
// fetch('/https://uczsieapp-mailer.herokuapp.com/', {
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
body = JSON.stringify(body);
console.log(body);
fetch('http://localhost:4000/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
content: body,
}).then(r => console.log(r)).catch(e => console.log(e));
}
这是我的节点代码:
var cors = require('cors');
var app = express();
app.use(cors());
var a = '=';
router.post('/', (req, res, next) => {
console.log('mailing');
console.log(a);
a += '=';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: 'someuser@gmail.com',
pass: 'testgmail'
}
});
console.log(req.body.content);
let mailOptions = {
from: `${req.body.name} ${req.body.email}`, // sender address
to: 'alexander.ironside@mygeorgian.ca', // list of receivers
subject: 'Email from UczSieApp contact form', // Subject line
text: 'Hello world ', // plaintext body
html: `
<h4>Imie: ${req.body.name}</h4>
<h4>Email: ${req.body.email}</h4>
<h4>Powod kontaktu: ${req.body.contactReason}</h4>
<p>Wiadomosc: ${req.body.additionalInfo}</p>
`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
);
如您所见,我正在使用cors module,它应该可以处理所有cors 问题。
但这还不够。当我摆脱传递给fetch() 的headers 属性时,调用正在完成,但没有发送数据。当我添加headers 时,我得到了乐趣
跨域请求被阻止:同源策略不允许读取位于http://localhost:4000/ 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
又报错了。
我怎样才能绕过它,我错过了什么?
我在编写代码时使用了这个答案:https://stackoverflow.com/a/42965820/7055769
【问题讨论】:
-
CORS 是出于安全原因,考虑到 cors 代码(希望)不会部署到生产环境中,我认为采用另一种方法要好得多,例如安装 nginx(或apache,或码头或任何其他可以反向代理您的呼叫的服务器)本地并将您的呼叫从前端服务器代理到快速服务器。
-
我只想从网站发送一封电子邮件。该数据库基于 Firebase,因此 Node 将无法连接到数据库。
-
CORS 发生在客户端(您的反应应用程序)和服务器(您的快递)之间。您想根据我在您的代码中看到的内容从服务器发送电子邮件,所以我的建议仍然适用。
标签: javascript node.js reactjs express cors