iT邦幫忙

0

[已解決]如何在Heroku執行即時聊天室

我用Laravel及Larasocket建立了一個即時聊天室,在localhost(127.0.0.1:8000)的環境下,能夠即時聊天,不過當我將即時聊天室host到Heroku時,沒辦法即時聊天,必須重新整理。

這是在localhost環境下的即時聊天室
https://imgur.com/gallery/39boNtz

這是在Heroku環境下的即時聊天室
https://imgur.com/gallery/Hyz6Vid

我的解決方法:
進入Heroku目標專案中的Setting,打開環境變數清單,填入兩個KEY及對應的VALUE。
分別是
BROADCAST_DRIVER :larasocket
LARASOCKET_TOKEN : 取得token

看更多先前的討論...收起先前的討論...
Han iT邦新手 4 級 ‧ 2020-11-20 16:07:27 檢舉
有去查看heroku log有沒有錯誤訊息嗎
有打開DevTools查看console,不過沒有跳出任何錯誤
Han iT邦新手 4 級 ‧ 2020-11-20 20:47:43 檢舉
heroku看server端的log有沒有噴錯,看client端沒錯誤就要確認server端
這是今天7:46 PM時,push的build log,系統顯示Build succeeded


-----> PHP app detected
-----> Bootstrapping...
-----> Installing platform packages...
- php (7.4.12)
- ext-mbstring (bundled with php)
- apache (2.4.46)
- nginx (1.18.0)
-----> Installing dependencies...
Composer version 1.10.17 2020-10-30 22:31:58
Loading composer repositories with package information
Installing dependencies from lock file
Package operations: 66 installs, 0 updates, 0 removals
- Installing doctrine/inflector (2.0.3): Loading from cache
- Installing doctrine/lexer (1.2.1): Loading from cache
- Installing dragonmantank/cron-expression (v3.0.2): Loading from cache
- Installing voku/portable-ascii (1.5.6): Loading from cache
- Installing symfony/polyfill-php80 (v1.20.0): Loading from cache
- Installing symfony/polyfill-mbstring (v1.20.0): Loading from cache
- Installing symfony/polyfill-ctype (v1.20.0): Loading from cache
- Installing phpoption/phpoption (1.7.5): Loading from cache
- Installing graham-campbell/result-type (v1.0.1): Loading from cache
- Installing vlucas/phpdotenv (v5.2.0): Loading from cache
- Installing symfony/css-selector (v5.1.8): Loading from cache
- Installing tijsverkoyen/css-to-inline-styles (2.2.3): Loading from cache
- Installing symfony/var-dumper (v5.1.8): Loading from cache
- Installing symfony/deprecation-contracts (v2.2.0): Loading from cache
- Installing symfony/routing (v5.1.8): Loading from cache
- Installing symfony/process (v5.1.8): Loading from cache
- Installing symfony/polyfill-php72 (v1.20.0): Loading from cache
- Installing symfony/polyfill-intl-normalizer (v1.20.0): Loading from cache
- Installing symfony/polyfill-intl-idn (v1.20.0): Loading from cache
- Installing symfony/mime (v5.1.8): Loading from cache
- Installing symfony/polyfill-php73 (v1.20.0): Loading from cache
- Installing symfony/http-foundation (v5.1.8): Loading from cache
- Installing symfony/http-client-contracts (v2.3.1): Loading from cache
- Installing psr/event-dispatcher (1.0.0): Loading from cache
- Installing symfony/event-dispatcher-contracts (v2.2.0): Loading from cache
- Installing symfony/event-dispatcher (v5.1.8): Loading from cache
- Installing psr/log (1.1.3): Loading from cache
- Installing symfony/error-handler (v5.1.8): Loading from cache
- Installing symfony/http-kernel (v5.1.8): Loading from cache
- Installing symfony/finder (v5.1.8): Loading from cache
- Installing symfony/polyfill-intl-grapheme (v1.20.0): Loading from cache
- Installing symfony/string (v5.1.8): Loading from cache
- Installing psr/container (1.0.0): Loading from cache
- Installing symfony/service-contracts (v2.2.0): Loading from cache
- Installing symfony/console (v5.1.8): Loading from cache
- Installing symfony/polyfill-iconv (v1.20.0): Loading from cache
- Installing egulias/email-validator (2.1.24): Loading from cache
- Installing swiftmailer/swiftmailer (v6.2.3): Loading from cache
- Installing ramsey/collection (1.1.1): Loading from cache
- Installing brick/math (0.9.1): Loading from cache
- Installing ramsey/uuid (4.1.1): Loading from cache
- Installing psr/simple-cache (1.0.1): Loading from cache
- Installing opis/closure (3.6.1): Loading from cache
- Installing symfony/translation-contracts (v2.3.0): Loading from cache
- Installing symfony/translation (v5.1.8): Loading from cache
- Installing nesbot/carbon (2.41.5): Loading from cache
- Installing monolog/monolog (2.1.1): Loading from cache
- Installing league/mime-type-detection (1.5.1): Loading from cache
- Installing league/flysystem (1.1.3): Loading from cache
- Installing league/commonmark (1.5.7): Loading from cache
- Installing laravel/framework (v8.15.0): Loading from cache
- Installing fideloper/proxy (4.4.1): Loading from cache
- Installing asm89/stack-cors (v2.0.2): Loading from cache
- Installing fruitcake/laravel-cors (v2.0.3): Loading from cache
- Installing psr/http-message (1.0.1): Loading from cache
- Installing psr/http-client (1.0.1): Loading from cache
- Installing ralouphie/getallheaders (3.0.3): Loading from cache
- Installing guzzlehttp/psr7 (1.7.0): Loading from cache
- Installing guzzlehttp/promises (1.4.0): Loading from cache
- Installing guzzlehttp/guzzle (7.2.0): Loading from cache
- Installing larasocket/larasocket-driver (1.0.3): Loading from cache
- Installing nikic/php-parser (v4.10.2): Loading from cache
- Installing dnoegel/php-xdg-base-dir (v0.1.1): Loading from cache
- Installing psy/psysh (v0.10.4): Loading from cache
- Installing laravel/tinker (v2.5.0): Loading from cache
- Installing laravel/ui (v3.1.0): Loading from cache
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: fideloper/proxy
Discovered Package: fruitcake/laravel-cors
Discovered Package: larasocket/larasocket-driver
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: nesbot/carbon
Package manifest generated successfully.
45 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
-----> Preparing runtime environment...
-----> Checking for additional extensions to install...
-----> Discovering process types
Procfile declares types -> web
-----> Compressing...
Done: 17.9M
-----> Launching...
Released v27

1 個回答

0
浩瀚星空
iT邦超人 1 級 ‧ 2020-11-20 17:58:37

如果沒錯誤訊息,推測你是用ajax式的。
畢竟如果是sock的話。理論會拿到sock連結失敗的錯誤。

推測你的ajax沒寫錯誤回傳。所以沒拿到錯誤。

我用的應該不是ajax,而是使用laravel broadcasting和vuejs。

resources\js\components\ChatsComponent.vue:

<script>
export default {
  data() {
    return {
      messages: [],
      newMessage: "",
    };
  },

  created() {
    this.fetchMessages();

//這個部分是所有在該頁面的人,都會處在名為"chat"的broadcast channel,並等待"MessageSentEvent"傳來的新訊息
    Echo.private("chat").listen("MessageSentEvent", (e) => {
      this.messages.push({
        message: e.message.message,
        user: e.user,
      });
    });
  },

  methods: {
    fetchMessages() {
      axios.get("/messages").then((response) => {
        this.messages = response.data;
      });
    },
    
    addMessage(message) {
      axios
        .post("/messages", {
          message,
        })
        .then((response) => {
          this.messages.push({
            message: response.data.message.message,
            user: response.data.user,
          });
        });
    },
    
//一旦使用者送出訊息後,會呼叫sendMessage函式,而sendMessage函式會呼叫addMessage函式,addMessage函式會將新訊息傳到MessageController做進一步的處理。

    sendMessage() {
      this.addMessage(this.newMessage);
      this.newMessage = "";
    },
  },
};
</script>

app\Http\Controllers\MessageController.php:

class MessageController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    public function index()
    {
        return Message::with('user')->get();
    }

    public function store(Request $request)
    {
        $user = Auth::user();
    
        $message = $user->messages()->create([
            'message' => $request->input('message')
        ]);

        // 訊息建立成功後,就會將新訊息傳給"MessageSentEvent"做進一步的處理。接著再將回傳值廣播給其他人
        broadcast(new MessageSentEvent($message, $user))->toOthers();
            
        return [
            'message' => $message,
            'user' => $user,
        ];
    }
}

app\Events\MessageSentEvent.php

class MessageSentEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $user;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message, User $user)
    {
        $this->message = $message;
        $this->user = $user;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
    //回傳新建好的私人"chat"Channel
        return new PrivateChannel('chat');
    }
}

routes\channels

Broadcast::channel('chat', function () {
    return \Illuminate\Support\Facades\Auth::check();
});

resources\js\bootstrap.js

import Echo from 'laravel-echo';
import Larasocket from 'larasocket-js';
window.Echo = new Echo({
     broadcaster: Larasocket,
     token: process.env.MIX_LARASOCKET_TOKEN,
});

你明明已經用了 axios 處理。
還在跟我說不是用ajax機制?

抱歉...感謝您的指教。問題已經解決了

我要發表回答

立即登入回答