![](/img/trans.png)
[英]HTML to Node.js server POST request on localhost with Fetch
[英]How to fix Fetch request to Node.js server?
我正在尝试使用 fetch 做一个简单的 POST 请求。 我正在尝试在前端使用 Vanilla Javascript、HTML、CSS 和在后端使用 Z3B2819/ExpressEEF 来创建联系表格。 这是我的前端代码:
<form id="sendMail">
<div>
<label for="name">Name: </label>
<input name="name" id="name" placeholder="Name">
</div>
<div>
<label for="email">Email: </label>
<input name="email" id="email" placeholder="Email">
</div>
<div>
<label for="phone">Phone: </label>
<input name="phone" id="phone" placeholder="Phone">
</div>
<div>
<label for="subject">Message: </label>
<input name="subject" id="subject" placeholder="How can we help you?">
</div>
<div>
<input type="submit">Send Message</input>
</div>
</form>
<script>
document.getElementById("sendMail").addEventListener('submit', sendMail);
function sendMail(e) {
e.preventDefault();
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let phone = document.getElementById("phone").value;
let subject = document.getElementById("subject").value;
console.log("sendMail fired!", name, email, phone, subject);
fetch('/api/contact', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({name: name, email: email, phone: phone, subject: subject}),
})
// .then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
这是我在后端的代码:
const http = require('http');
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static("express"));
// default URL for website
app.use('/', function(req,res){
res.sendFile(path.join(__dirname+'/express/index.html'));
//__dirname : It will resolve to your project folder.
});
const server = http.createServer(app);
const port = 4040;
const nodemailer = require('nodemailer');
app.post('/api/contact', async(req, res, next) => {
const { name, email, phone, subject } = req.body;
console.log("sendMail fired: ", req.body, name, email, phone, subject);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myEmailAddress',
pass: 'myPassword',
}
});
let mailOptions = await transporter.sendMail({
from: `info@companyemailaddress`,
to: `${email}`,
subject: `company`,
text:
`${name}, \n\n` +
`Thank you for contacting company! A representative will contact you within 2 business days. \n\n` +
`If you have any further question, feel free to email us at: \n\n` +
`info@company \n\n` +
`- company Automated Message`
});
console.log('Message sent: %s', mailOptions.messageId);
// console.log('Preview URL: %s', nodemailer.getTestMessageUrl(mailOptions))
let mailOptions2 = await transporter.sendMail({
from: `info@companyemail address`,
to: `myEmail`,
subject: `company`,
text:
`Name: ${name}, \n\n` +
`Email: ${email}, \n\n` +
`Phone: ${phone}, \n\n` +
`Subject: ${subject}, \n\n`
});
console.log('Message sent: %s', mailOptions2.messageId);
res.send('Email sent!')
})
server.listen(port);
console.debug('Server listening on port ' + port);
当我点击前端的“提交”输入时,我得到了一个成功的响应,没有任何服务器错误消息,但是当我查看我的服务器 console.logs 时,它什么也没显示 - 好像服务器没有被触及。 如果我只是在不是 JSON.stringify() 的 post 请求的正文中发送 object,则服务器会给出错误消息,指出正文中的 ZA8CFDE6331BD59EB2AC96F8911C4B666 存在问题。 所以看起来 POST 请求正在成功地联系服务器。 但什么也没有发生。
我究竟做错了什么?
您应该将根路由从app.use
为app.get
当您在/
上使用app.use
时,它会匹配任何带有任何 http 动词的路由并充当全局中间件。
因此,您的发布请求实际上与该app.use
匹配,而您的实际app.post
从未有机会执行。
您可以使用 postman 测试您的 api,然后为您生成获取请求。 在您的情况下,您应该将完整的 uri 作为 args 放入您的 fetch 调用中。
fetch('http://example.com/movies.json')
.then(response => response.json()).then(console.log);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.