【发布时间】:2020-10-29 05:19:03
【问题描述】:
我正在尝试运行执行 HTTP 和 Websocket 请求的服务器。 HTTP 请求将用于从名为“geo-data.json”的本地文件中提取数据,我需要使用 D3.js 和 topojson 库显示纽约市的地图。
我正在使用 Node.js 来运行服务器。我的 package.json 文件如下所示:
{
"name": "inputusername_showlistofusers",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"node-geocoder": "^3.27.0",
"ws": "^7.3.0"
}
}
我在客户端的 Websocket 配置如下所示:
var wsUri = "ws://localhost:8080";
var ws = new WebSocket(wsUri);
ws.onopen = function (evt) {
console.log("1. Connected (from Client)")
}
ws.onmessage = function (message) {
var messageArray = JSON.parse(message.data)
console.log("5. This is the list of user names:", messageArray)
}
另外,在客户端,我包含了我的 D3 代码,以使用 D3.json 从“geo-data.json”和“nyc-streets.json”文件中读取地理数据:
d3.json('geo-data.json', function (error, data) {
//code
}
d3.json('nyc-streets.json', function (error, data) {
//code
}
在服务器端,我使用 Websockets 来广播消息。代码如下所示:
var WebSocket = require("ws");
wss = new WebSocket.Server({ port: 8080 });
wss.on("connection", function connection(ws) {
console.log("2. Connected (from Server)")
ws.on("message", function incoming(message) {
console.log("3. received from the client ", message);
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
console.log("7. All names connected: ", message)
}
})
})
})
问题:当我使用“node server.js”运行 server.js 时,需要 Websocket 的代码(客户端和服务器上)运行顺利,但需要 https 的代码却没有:
d3.json('geo-data.json', function (error, data)
我收到以下错误(我正在使用 File/Users... 打开 index.html 文件):
CORS 已阻止从源“null”访问“file:///Users...”处的 XMLHttpRequest
策略:跨域请求仅支持协议方案:http、data、chrome、chrome-extension、https。
所以我尝试使用 http-server 来运行服务器并通过对 package.json 进行以下更改来解决此问题:“scripts”:{start:“index.html”} 但是,现在 Websocket 代码没有工作,我收到以下错误:
(index):112 WebSocket 连接到“ws://localhost:8080/”失败:WebSocket 握手期间出错:意外响应代码:200
如何同时发出 HTTP 和 Websocket 请求?
提前致谢。
【问题讨论】:
标签: javascript node.js json d3.js websocket