使用 HTTP(S) 将客户端连接到 Node.js 服务器
Connect client to Node.js server with HTTP(S)
用户 'gather' 本地电脑上的数据,他们需要能够将其上传到服务器。
我像这样设置了一个简单的 node.js 服务器:
var https = require('https');
var fs = require('fs');
var path = require('path');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
var server = https.createServer(options, function (request, response) {
response.writeHead(200, {'Content-Type': 'text/bold'});
response.end("Server is running");
});
现在我想使用 httprequest 将客户端连接到它。我试过 JQuery/XMLhttpRequest 但我收到跨源资源共享错误(我知道为什么但我认为我真的不想禁用此保护)。我认为可以使用套接字建立连接,但我不确定这是否是一个好的选择。我宁愿使用 HTTP 请求。
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://localhost/file.txt', true);
xmlhttp.send();
//JQuery get
$.get("http://127.0.0.1:1337")
有什么遗漏吗?欢迎提问。
只是一个提示:如果您的客户端应用程序页面不是从您的服务器组件所在的同一域呈现的 运行,那么您将收到此类错误。此错误意味着您的页面将从另一台服务器访问资源,而不是从其来源的服务器访问资源。所有的浏览器都有这样的限制。您可以在您的服务器上配置以允许从其他域(托管您的客户端应用程序的域)进行访问,或者从同一域托管客户端应用程序和服务器。
将第二组代码中的 http://
更改为 https://
。同源包括 scheme/protocol。 (无论如何,您的服务器代码似乎只会启动一个 https
侦听器。:))。
用户 'gather' 本地电脑上的数据,他们需要能够将其上传到服务器。
我像这样设置了一个简单的 node.js 服务器:
var https = require('https');
var fs = require('fs');
var path = require('path');
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
var server = https.createServer(options, function (request, response) {
response.writeHead(200, {'Content-Type': 'text/bold'});
response.end("Server is running");
});
现在我想使用 httprequest 将客户端连接到它。我试过 JQuery/XMLhttpRequest 但我收到跨源资源共享错误(我知道为什么但我认为我真的不想禁用此保护)。我认为可以使用套接字建立连接,但我不确定这是否是一个好的选择。我宁愿使用 HTTP 请求。
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://localhost/file.txt', true);
xmlhttp.send();
//JQuery get
$.get("http://127.0.0.1:1337")
有什么遗漏吗?欢迎提问。
只是一个提示:如果您的客户端应用程序页面不是从您的服务器组件所在的同一域呈现的 运行,那么您将收到此类错误。此错误意味着您的页面将从另一台服务器访问资源,而不是从其来源的服务器访问资源。所有的浏览器都有这样的限制。您可以在您的服务器上配置以允许从其他域(托管您的客户端应用程序的域)进行访问,或者从同一域托管客户端应用程序和服务器。
将第二组代码中的 http://
更改为 https://
。同源包括 scheme/protocol。 (无论如何,您的服务器代码似乎只会启动一个 https
侦听器。:))。