我有一个 html文件,index.html
其中script.js
使用.localhost:8080
NodeServer.js
Node.js
我希望这样,每当我在输入框中输入数据时,它应该由本地脚本获取,然后将其
script.js
导出到NodeServer.js
应用程序,这将进一步在控制台上记录数据。我正在使用 Chrome 浏览器 -
65.0.3325.181
这是我的index.html
:
<!DOCTYPE html>
<html>
<head>
<title>Website</title>
<!-- My local script -->
<script src='file:///F:/RahulVerma/NodeJS/LoginPage/script.js'></script>
</head>
<body>
<input type='text' placeholder='Enter username' id='username'/><br/>
<input type='password' placeholder='Enter password' id='password'/><hr/>
<!-- getData() is present in local script -->
<button onclick='getData();'>Submit</button>
</body>
</html>
这是我的script.js
:
let getData = () => {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
module.exports = { username, password }; // exporting username and password to server running through node.js
}
我的NodeServer.js
:
const http = require('http'); // to create server
const fs = require('fs'); // to read index.html
const script = require('F:/RahulVerma/NodeJS/LoginPage/script'); // to fetch data from script.js
// My Server
let server = (request, response) => {
fs.readFile('F:/RahulVerma/NodeJS/LoginPage/index.html', 'utf8', (error, result) => {
if(error) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write(`Error: ${error}`);
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(result);
}
response.end();
});
}
// Creating server
http.createServer(server).listen(8080);
console.log(script.username, script.password); // logging data onto the console
当我在 Node.js 9.3.0 (ia32) 和 npm 中键入 node NodeServer.js 时,index.html
开始工作localhost:8080
但script.js
由于以下错误而无法在浏览器中呈现:Not allowed to load local resource: file:///F:/RahulVerma/NodeJS/LoginPage/script.js
我究竟做错了什么 ?