Node.js服务中网页script加载失败,如何实现输入数据传递至服务器?
问题分析与解决方案
你遇到的问题主要有两个核心原因:浏览器的安全限制,以及对浏览器端JS和Node.js运行环境的误解,咱们一步步来解决:
1. 为什么script.js加载失败?
浏览器出于安全考虑,不允许从http://localhost:8080这种HTTP协议的页面,加载file://协议的本地资源(这违反了同源策略的安全规则)。你不能直接在HTML里用file://路径引用脚本,得让你的Node服务器来托管这个静态文件。
2. 为什么数据传递的方式完全错误?
module.exports是Node.js专属的CommonJS模块语法,浏览器根本不认识这个语法。而且浏览器和Node服务器是两个完全独立的运行环境,你没法直接把浏览器里的变量"导出"给服务器,必须通过HTTP请求(比如POST)来传递数据。
修正后的完整代码
第一步:修改index.html
把script的引用改成相对路径,让Node服务器来提供这个文件:
<!DOCTYPE html> <html> <head> <title>Website</title> <!-- 用相对路径,让Node服务器托管这个脚本 --> <script src='/script.js'></script> </head> <body> <input type='text' placeholder='Enter username' id='username'/><br/> <input type='password' placeholder='Enter password' id='password'/><hr/> <button onclick='getData();'>Submit</button> </body> </html>
第二步:修改script.js
去掉module.exports,改用fetch发送POST请求把数据传给服务器:
function getData() { const username = document.getElementById('username').value; const password = document.getElementById('password').value; // 用POST请求把数据发给Node服务器 fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password }), }) .then(response => response.text()) .then(data => console.log('Server response:', data)) .catch(error => console.error('Error:', error)); }
第三步:修改NodeServer.js
现在要做三件事:
- 处理HTML页面的请求
- 处理静态文件(比如script.js)的请求
- 处理POST请求,解析并打印数据
const http = require('http'); const fs = require('fs'); const path = require('path'); const server = (request, response) => { // 处理POST请求(接收前端传来的数据) if (request.method === 'POST') { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { const { username, password } = JSON.parse(body); console.log('Received data:', username, password); // 控制台打印数据 response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Data received successfully'); }); return; } // 处理GET请求,返回对应的文件 let filePath = '.' + request.url; if (filePath === './') { filePath = './index.html'; // 默认返回index.html } const extname = path.extname(filePath); let contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; } fs.readFile(filePath, 'utf8', (error, result) => { if (error) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.write(`Error: ${error}`); } else { response.writeHead(200, {'Content-Type': contentType}); response.write(result); } response.end(); }); }; http.createServer(server).listen(8080); console.log('Server running at http://localhost:8080/');
运行步骤
- 确保三个文件在同一个目录下(或者调整路径匹配你的实际位置)
- 在终端运行
node NodeServer.js - 打开Chrome访问
http://localhost:8080,输入用户名和密码,点击提交 - 你就能在Node的控制台看到打印出的用户名和密码了
内容的提问来源于stack exchange,提问作者user9090230
相关产品推荐
相关产品推荐

