[英]Run a node.js server with html-website that interacts with the website
我是node.js和javascript的新手,想學習基礎知識。 所以我要做的是運行一個托管html網站的服務器。 在該html網站上應該是一個輸入文本字段和一個“發送”按鈕。 每次單擊發送時,我在輸入文本字段中編寫的文本都應發送到服務器並打印在控制台上。 到目前為止,我已經嘗試了一些方法,但是沒有任何效果。
這是server.js的代碼:
var http = require('http');
var fs = require('fs');
function handleRequest(request, response) {
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("./index.html").pipe(response);
}
}
var server = http.createServer(handleRequest);
server.listen(3000);
這是html網站的代碼:index.html
<html>
<head>
<title>title</title>
</head>
<body>
<h1>text field</h1>
<input type="text" id="input1" name="input1">
<input type="submit" id="submitinput1" value="Send" onclick="sendClick()">
</body>
</html>
有人可以解釋一下我如何將文本字段與服務器“連接”,以便可以進行交互嗎?
為了簡化網站的創建,您可以使用express。
要安裝它,只需執行: npm install express --save
--save選項是將依賴項保存到package.json中
這是帶有介紹和文檔的官方網站:
一些教程:
https://scotch.io/tutorials/use-expressjs-to-deliver-html-files
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.