如何使我的vue组件连接到我的节点服务器

时间:2017-07-14 03:14:34

标签: node.js express socket.io vue.js

嘿,我们正在使用 Vuejs作为前端和Laravel 5.4为我的后端API构建SPA(单页应用程序)聊天应用程序。 为了实现实时通信体验,我在我的vue前端项目上构建了一个带有express并安装 vue-socket.io 的基本节点服务器,但是vue项目似乎没有连接到节点服务器。请问我在这里失踪了什么? 这就是我所做的:

server.js

var app = require('express')();

var server = require('http').Server(app);

var io = require('socket.io')(server);

var redis = require('redis');

app.get('/', function(req, res){
  res.send('<h1>Hello world</h1>');
});

function logData(message) {
    var d = new Date();
    var time = '[' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] '
    console.log(time + message);
}

function logMultipleData(message, channel, data) {
    var d = new Date();
    var time = '[' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] '
    console.log(time + message + channel + data);
}

server.listen(3000, function() {
    logData('Chat server booted on *:3000');
});

io.on('connection', function(socket) {
    console.log('new client connected');
    var redisClient = redis.createClient();
    redisClient.subscribe('message');
    redisClient.on('message', function (channel, message) {
        logMultipleData('New Message In Queune', channel, message);
    })
});

Main.js (此文件位于vue前端项目中)

import Vue from 'vue'
import App from './App.vue'
import Router from './routes.js'

import VueResource from 'vue-resource'

import VueSocketIO from 'vue-socket.io'; 

Vue.use(VueResource)
Vue.use(VueSocketIO, 'http://localhost.com:8890');

new Vue({
  el: '#app',
  render: h => h(App),
  router: Router
})

Test.vue (我的测试组件)

<template>
<!--Mask-->
<div class="view">
  <img class="background" src="/src/assets/images/background.jpg" alt="">
  <!--Intro content-->
  <div class="full-bg-img flex-center">
    <div class="container">
      <div class="row">

        <div class="col-lg-4 offset-4">
          <!--Form with header-->
          <div class="card section">

            <div class="progress">
              <div class="indeterminate" style="width: 70%"></div>
            </div>

            <div class="card-block">


              <!--Header-->
              <!-- <div class="form-header  purple darken-4">
                <h3><i class="fa fa-lock"></i> Register:</h3>
              </div> -->

              <!--Body-->
              <button @click="clickButton">Ping Server</button>
              <blockquote class="blockquote bq-primary">
                <!-- <p class="bq-title">User Name</p> -->
                please enter a username or take one of the suggestions below.
              </blockquote>

               <form v-on:submit.prevent="handleLoginFormSubmit()">
                <div class="md-form">
                  <!-- <i class="fa fa-envelope-o prefix"></i> -->
                  <input type="text" placeholder="Email / Username" id="email" v-model="login.email" class="form-control validate" required autofocus>
                  <div class="error-log"></div>
                </div>

                <div class="text-center">
                  <button id="load-btn" class="btn btn-deep-purple" disabled><set-loader></set-loader></button>
                  <button id="login-btn" class="btn btn-deep-purple">Login</button>
                </div>
              </form>


            </div>

            <!--Footer-->
            <div class="modal-footer">
              <!-- Stepers Wrapper -->
              <ul class="stepper stepper-horizontal">

                <!-- First Step -->
                <li class="active">
                  <a href="#!">
                                                    <span class="circle">1</span>
                                            </a>
                </li>

                <!-- Second Step -->
                <li class="">
                  <a href="#!">
                                                    <span class="circle">2</span>
                                            </a>
                </li>

                <!-- Third Step -->
                <li class="">
                  <a href="#!" disabled>
                                                    <span class="circle">3</span>
                                            </a>
                </li>

                <!-- Fourth Step -->
                <li class="">
                  <a href="#!" disabled>
                                                    <span class="circle">4</span>
                                            </a>
                </li>
              </ul>
            </div>
          </div>
          <!--/Form with header-->
        </div>
      </div>
    </div>
  </div>
  <!--/Intro content-->
</div>
<!--/.Mask-->
</template>

<script>
import Vue from 'vue'
import VueSocketIO from 'vue-socket.io';
import Chip from './helper/chipNoavatar.vue'
import Loader from './helper/loaders/multicolors/small.vue'
Vue.use(VueSocketIO, 'http://localhost.com:3000');
export default {
  components: {
    'set-chip': Chip,
    'set-loader': Loader
  },
  data() {
    return {
      login: {
        email: '',
      }
    }
  },
  created() {

  },
  sockets:{
    connect: function(){
      console.log('socket connected')
    },
    disconnect: function(){
      console.log('socket disconnected')
    },
    customEmit: function(val){
      console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
    }
  },
  mounted() {
    //do something after mounting vue instance
    // Data Picker Initialization
    // $('.datepicker').pickadate({
    //   min: new Date(1910, 0, 0),
    //   max: new Date(2012, 0, 0)
    // });
  },
  methods: {
    handleLoginFormSubmit() {
        // $("#login-btn").hide()
        // $("#load-btn").show()

        var postData = {
          client_id: 2,
          client_secret: this.$afrobukConfig.client_secret,
          grant_type: 'password',
          username: this.login.email,
          remember: true
        }

        this.$http.post("api/test", postData)
          .then(response => {

            console.log(response.body)
          })
          .catch(function(error) {
            console.log(error);
          });
    },

    clickButton: function(val){
        // $socket is socket.io-client instance
        this.$socket.emit('emit_method', val);
    }
  }
}
</script>

<style>
</style>

请有人帮我这个吗?感谢

1 个答案:

答案 0 :(得分:2)

一些事情。首先,我假设你使用的是vue-cli webpack启动器,因为你有一个main.js和一个.vue文件。

您只需要在main.js的前端使用socket.io中间件。这将为所有允许您与套接字交互的组件添加$ socket属性。您应该从Vue.use(SocketIO)

中删除Test.vue

其次,在main.js中,您将连接设置为

Vue.use(VueSocketIO, 'http://localhost.com:8890');

什么时候应该

Vue.use(VueSocketIO, 'http://localhost:3000');

localhost.com不是您的套接字服务器。如果您的套接字服务器在dns或您的主机文件中,它将类似myserver.domain.com,但由于您在同一台机器上运行套接字服务器和vue前端,您可以使用localhost或{{1} (在大多数情况下)作为服务器地址

如果您想使用端口8890,则需要更改

127.0.0.1

server.listen(3000, function() {

在您的服务器代码中。