正如我的标题所暗示的那样,我正在尝试在我的react项目中实现Sendgrid。我正在将节点后端与快速服务器和前端的react-router一起使用。在另一个线程上也提出了类似的问题,但不知道安装适当的react-router是否会使过程复杂化。这是我的代码:
前端
onFormSubmit = (e) => {
e.preventDefault();
if (!this.state.name || !this.state.email || !this.state.message) {
this.setState(() => ({ error: 'Please fill out all the above fields!' }));
} else {
this.setState(() => ({ error: '' }));
fetch('/contact', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message
})
})
.catch((error) => {
console.error(error);
});
}
}
后端(服务器设置)
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 8080;
const sgMail = require('@sendgrid/mail');
app.use(express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.post('/contact', (req, res) => {
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'email',
from: 'email',
subject: 'New Message From Portfolio',
text: 'test',
html: '<strong>and easy to do anywhere, even with
Node.js</strong>',
};
sgMail.send(msg);
})
app.listen(port, () => {
console.log('Server is running');
});
运行此代码时,出现未找到404的“ / contact”。从概念上讲,我认为我来对地方了,但很好奇为什么我的前端不认识这条路。我正在从/ contact路线获取信息,并且在服务器上有相应的快递信息。