使用脚本从网页检索数据,然后使用节点js server

时间:2018-05-21 11:41:10

标签: javascript html node.js server

我在index.html中使用script.js中的脚本localhost:8080运行了一个html文件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>
&#13;
&#13;
&#13;

这是我的script.js

&#13;
&#13;
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
}
&#13;
&#13;
&#13;

我的NodeServer.js

&#13;
&#13;
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
&#13;
&#13;
&#13;

当我在Node.js 9.3.0(ia32)和npm中键入节点NodeServer.js时,index.html开始处理localhost:8080,但script.js无法在浏览器中呈现由于以下错误:Not allowed to load local resource: file:///F:/RahulVerma/NodeJS/LoginPage/script.js

我做错了什么?

1 个答案:

答案 0 :(得分:0)

cors error:一种机制,它使用额外的HTTP标头让用户代理获得从不同来源的服务器访问所选资源的权限

// Create our server
var server;
server = http.createServer(function(req,res){
// Set CORS headers
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");;
if ( req.method === 'OPTIONS' ) {
    res.writeHead(200);
    res.end();
    return;
}
});

进一步澄清访问stack overflow cors

最佳awnser link