每當我使用 VS Code 在實時服務器上運行我的應用程式時,我都會收到無法獲取錯誤。我最好的猜測是這與我的路由不正確有關,我只是不確定我的路由是錯誤的。任何形式的幫助表示贊賞 <3
目標是在應用程式完成時發送一個 POST 請求,并將用戶的電子郵件輸入到表單元素中。
應用程式.js
const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
//Middleware
app.use(express.json());
app.use(bodyParser.urlencoded({extended: false}));
console.log("The directory is:", (path.join(__dirname, '/site')));
app.use(express.static(path.join(__dirname, '/site')));
app.post('/', (req, res) => {
console.log('hey!');
});
app.listen(5000, console.log('Server started!'))
登陸.html
<form action="/subscribe" method="POST">
<div class="newsletter-form-grp">
<i class="far fa-envelope"></i>
<input name="email" id="email" required pattern="[a-z0-9.% -] @[a-z0-9.-] \.[a-z]{2,4}$" type="email" placeholder="Enter your email...">
</div>
<button id="cta">SUBSCRIBE <i class="fas fa-paper-plane"></i></button>
</form>
land.html 里面的 JS 代碼
<script>
//form submission
let cta = document.getElementById('cta');
let email = document.getElementById('email').value;
let status = document.getElementById('status');
cta.addEventListener('click', (event) => {
event.preventDefault();
if(this.email.value == null || this.email.value == "") {
status.classList.add('statusShow');
} else {
let fetchData = {
method: 'POST',
body: JSON.stringify({email: this.email.value, js: true}),
headers: {"Content-Type": "application/json"}
}
fetch('/subscribe', fetchData)
.then(res => {
if(res.ok) {
// yay
} else {
status.classList.add('statusShow');
}
})
}
});
</script>
JSON 包
{
"name": "Main",
"version": "1.0.0",
"description": "",
"main": "site/js/app.js",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"index": "^0.4.0",
"request": "^2.88.2"
},
"devDependencies": {
"nodemon": "^2.0.15"
},
"scripts": {
"serve": "node app",
"dev": "nodemon app"
},
"keywords": [],
"author": "",
"license": "ISC"
}
專案樹:https : //imgur.com/a/B9Ucrap
uj5u.com熱心網友回復:
您的landing.html 是一個靜態檔案(在site檔案夾中?),而且您也沒有在Express 中定義GET 路由來提供此頁面。因此,為了從瀏覽器訪問它,您需要使用:http://localhost:5000/landing.html。
你的表格說:<form action='/subscribe' action='POST'>。因此,您的 Express 需要定義此路由:
app.post("/subscribe", (req, res) => {
console.log("hey!");
res.send("got it!");
});
順便說一句,您的 Html 沒有包含idof的元素status。您的訂閱按鈕單擊事件代碼將出錯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364404.html
標籤:javascript html css 节点.js 表达
上一篇:如何在Nodejs中創建嵌套架構
