require 和 import 不适用于 vue.js 中的节点库

require and import not working for node libraries in vue.js

所以我正在尝试将 nodejs 库 net 导入到 vuejs 项目中。但是我无法导入库。我已经尝试使用 const net = require('net')const net = require('net').defaultimport * as net from 'net',但是这些工作的 none 和对象是空的(如果我 console.log() 它,或者抛出Uncaught TypeError: Cannot read property 'createServer' of undefined。我也尝试过同时使用 yarnnpm,但没有成功。

net 模块肯定在我的 node_modules/ 文件夹中。

组件文件

<template>
    <p>charts placeholder</p>
</template>

<script>
    const net = require('net').default;
    console.log(net);
    const port = 8080;
    const host = '127.0.0.1';

    let server = net.createServer(function(socket) {
        socket.on('data', function(data){
            let str = data.toString();
            console.log(str);
            try {
                let json = JSON.parse(str);
                console.log(json);
            } catch (e) {
                console.log('error str: ' + str);
            }

        });
        socket.on('error', function(err) {
            console.log(err)
        })
    });

    server.listen(port, host);


    export default {
        name: "Charts"
    }
</script>

<style scoped>

</style>

任何建议都将非常感谢。

这不是前端框架的重点。如果你想让数据对你的 Vue 应用程序可用,你应该使用一个单独的项目并 运行 它们分开。

要在前端和后端之间交换数据,您可以使用 axios 或其他工具:https://vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#ad