![](/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.