簡體   English   中英

使Node.js代碼在瀏覽器中工作

[英]Making node.js code work in browser

我對Node.js相當陌生,並正在創建一個普通的聊天應用程序以了解更多信息。 我正在使用ws庫

在我的實驗中,我發現node.js代碼不能直接在瀏覽器中運行(我更具體地要求()。) 因此,要使其在瀏覽器中工作,我必須使用browserify將代碼轉換為與瀏覽器兼容。

但是,轉換后的代碼將引發未定義函數的錯誤

我的node.js代碼

var WebSocket = require('ws')
  , ws = new WebSocket('ws://localhost:8080');
ws.on('open', function() {
    var firstMessage = '{"type":"name","message":"god"}';
    ws.send(firstMessage.toString());
});
ws.on('message', function(message) {
    console.log('received: %s', message);
});

我使用browserify轉換的代碼

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

/**
 * Module dependencies.
 */

var global = (function() { return this; })();

/**
 * WebSocket constructor.
 */

var WebSocket = global.WebSocket || global.MozWebSocket;

/**
 * Module exports.
 */

module.exports = WebSocket ? ws : null;

    /**
     * WebSocket constructor.
     *
     * The third `opts` options object gets ignored in web browsers, since it's
     * non-standard, and throws a TypeError if passed to the constructor.
     * See: https://github.com/einaros/ws/issues/227
     *
     * @param {String} uri
     * @param {Array} protocols (optional)
     * @param {Object) opts (optional)
     * @api public
     */

    function ws(uri, protocols, opts) {
      var instance;
      if (protocols) {
        instance = new WebSocket(uri, protocols);
      } else {
        instance = new WebSocket(uri);
      }
      return instance;
    }

    if (WebSocket) ws.prototype = WebSocket.prototype;

    },{}],2:[function(require,module,exports){
    var WebSocket = require('ws')
      , ws = new WebSocket('ws://localhost:8080');
      console.log(ws);
    ws.on('open', function() {   //line that contains error
        var firstMessage = '{"type":"name","message":"Ayush"}';
        ws.send(firstMessage.toString());
    });
    ws.on('message', function(message) {
        console.log('received: %s', message);
    });
    },{"ws":1}]},{},[2]);

我的服務器代碼

var WebSocketServer = require('ws').Server
  , wss = new WebSocketServer({port: 8080});

var index = 0;
var map = {};
wss.on('connection', function(ws) {
    map[index] = ws;
    var myindex = index;
    var username;
    index++;
    ws.on('message', function(message) {
        var json = JSON.parse(message);
        if(json.type == "name"){
            username = json.message;
            console.log(username);
        } else {
            //Print Message
        }
    });
    ws.send('something');

    ws.on('close', function(){
        console.log("Deleting index" + myindex);
        delete map[myindex];
    });
});

但是,當我使用browserify並使用轉換后的代碼時,它將在第50行引發錯誤。

Uncaught TypeError:undefined不是 ws.open上的函數

ws庫建立在原始TCP套接字之上。 出於安全原因,您不能在客戶端JavaScript中使用它們,因此將無法正常工作。 您需要在瀏覽器中使用WebSocket構造函數。

唯一可以成功瀏覽的node.js庫是那些不使用node.js標准庫的庫-文件系統,網絡等。即,實用工具庫,例如underscoreasync

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM