Post 404 not found ошибка

Моя задача — это отправить к серверу запрос с двумя параметрами login и password и распарсить ответ в JSON-формате, который он мне вернёт.

У меня есть самописный скрипт запущенный на сервере:

import sqlite3
from flask import Flask, jsonify, request, abort
import json

app = Flask('__name__')

def register(login, password, data=""):
    insert_data = (login, password, data)
    conn = sqlite3.connect("users.db")
    cursor = conn.cursor()

    x = cursor.execute(" SELECT * FROM users WHERE login=?", (login,)).fetchall()

    if not x:
        cursor.execute("INSERT INTO users VALUES (?,?,?)", insert_data)
        conn.commit()
        return "OK"
    return "Username is registered"

def login(login, password):
    insert_data = (login, password)
    conn = sqlite3.connect("users.db")
    cursor = conn.cursor()

    x = cursor.execute(" SELECT data FROM users WHERE login=? AND password=?", (login,password)).fetchone()

    if not x:
        return "Login or password is incorrect"
    return {"status": "logged in", "data": x[0]}

def delete(login, password):
    insert_data = (login, password)
    conn = sqlite3.connect("users.db")
    cursor = conn.cursor()

    x = cursor.execute(" SELECT data FROM users WHERE login=? AND password=?", (login,password)).fetchone()

    if not x:
        return "Login or password is incorrect"
    x = cursor.execute(" DELETE FROM users WHERE login=? AND password=?", (login,password)).fetchone()
    conn.commit()
    return "user deleted"

#=======================================================================================

@app.route('/register', methods=['POST'])
def write_reg():
    if not request.json:
        print(request.json)
        abort(404)

    user = {"login": request.json["login"],
              "password": request.json["password"],
              "data": request.json.get("data") or ""}
    return register(**user), 201

@app.route('/login', methods=['POST'])
def write_log():
    if not request.json:
        print(request.json)
        abort(404)

    user = {"login": request.json["login"],
              "password": request.json["password"]}
    return login(**user), 201

@app.route('/delete', methods=['POST'])
def write_del():
    if not request.json:
        print(request.json)
        abort(404)

    user = {"login": request.json["login"],
              "password": request.json["password"]}
    return delete(**user), 201

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Not enought data'}), 404

if __name__ == '__main__':
    app.run(host='0.0.0.0',debug=True, threaded=True, port=5123)

POST-запрос отправляю вот таким образом:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + "?" + Data);

request.Method = "POST";
request.Accept = "application/json";
request.UserAgent = "Mozilla/5.0....";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
response.Close();

И получаю ошибку 404:

System.Net.WebException: "Удаленный сервер возвратил ошибку: (404) Не найден."

Подскажите, в чём дело? При отправке аналогичного запроса через консоль с помощью httpie всё проходит нормально и ответ возвращается:

HTTP/1.0 201 CREATED
Content-Length: 43
Content-Type: application/json
Date: Mon, 07 Sep 2020 09:49:10 GMT
Server: Werkzeug/0.16.0 Python/3.7.7

{
    "data": "",
    "status": "logged in"
}

Are your WordPress posts returning a 404 error on your website?

This error happens when you can access your WordPress admin area and blog, but when you try to open a post, you will see “404 Not Found”.

In this article, we will show you how to fix the WordPress posts returning 404 error.

How to fix WordPress posts returning 404 error

What Causes the WordPress Posts Returning 404 Error?

WordPress is a powerful content management system (CMS), but a slight change can sometimes make your WordPress website inaccessible.

In some cases, you may not be able to access your WordPress admin area or the website itself, like with the internal server error or error establishing a database connection.

By contrast, when your WordPress posts are returning 404 errors, you will still be able to get into your admin area and see your WordPress website on the front end. Then, when you click on a blog post, you will see a message saying “404 Not Found”.

Although this error message can be scary, it doesn’t mean you have lost your WordPress posts. Instead, your .htaccess file has probably been deleted, or something went wrong with the rewrite rules on your blog.

That being said, let’s look at how to fix the WordPress posts returning 404 error. You can use the links below to jump straight to different solutions.

  • Video Tutorial
  • Fix Your Permalink Settings
  • Update the WordPress .htaccess File
  • Contact Your Hosting Provider
  • Fix for Local Servers

Video Tutorial

Subscribe to WPBeginner

If you’d prefer written instructions, then just continue reading.

Fix Your Permalink Settings

WordPress posts can return 404 errors because of problems with rewrite rules in your .htaccess file. In most cases, you can fix the problem by updating your permalink settings.

Simply go to Settings » Permalinks in your WordPress admin, and click on the ‘Save Changes’ button.

Check Permalinks

This will update your permalink settings and flush the rewrite rules.

In most cases, this solution fixes the WordPress posts 404 error. However, if it does not work for you, then you probably need to update your .htaccess file manually.

Update the WordPress .htaccess File

First, you will need to connect to your server using an FTP client or the File Manager app in your WordPress hosting dashboard.

Next, you will need to find and edit the .htaccess file, which is located in the same location as folders like /wp-content/ and /wp-includes/.

Simply right-click on the file and select ‘File permissions’.

.htaccess file permissions

You can make the file writeable by changing its permissions to 666.

Simply enter ‘666’ into the ‘Numeric value’ box and then click on ‘OK’.

Change file attributes for the .htaccess file to 666

Then, you need to repeat the steps in the Fix the Permalinks Settings section of our tutorial. Once you have done this, don’t forget to change the permissions back to 660.

You can also edit the file and add code to it.

Edit .htaccess file

Once you have opened the .htaccess file with a text editor, simply insert this code.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Contact Your Hosting Provider

If neither of the solutions above has fixed the WordPress posts returning 404 error, then we recommend contacting your WordPress hosting provider. There may be an error on their end, or they might be able to help you troubleshoot the problem.

Please also see our guide on how to properly ask for WordPress support and get it.

Fix for Local Servers

If you are using a local server for testing purposes, then you will need to enable the rewrite_module in the Apache configuration of your MAMP, WAMP, or XXAMP site.

We hope this article helped you resolve the posts returning 404 error in WordPress. You may also want to see our guide to the most common WordPress errors and how to fix them, along with our expert picks for the best WordPress plugins to grow your site.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

Editorial Staff

Once you have opened the .htaccess file with a text editor, simply insert this code.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Contact Your Hosting Provider

If neither of the solutions above has fixed the WordPress posts returning 404 error, then we recommend contacting your WordPress hosting provider. There may be an error on their end, or they might be able to help you troubleshoot the problem.

Please also see our guide on how to properly ask for WordPress support and get it.

Fix for Local Servers

If you are using a local server for testing purposes, then you will need to enable the rewrite_module in the Apache configuration of your MAMP, WAMP, or XXAMP site.

We hope this article helped you resolve the posts returning 404 error in WordPress. You may also want to see our guide to the most common WordPress errors and how to fix them, along with our expert picks for the best WordPress plugins to grow your site.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience building WordPress websites. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.

404 Not Found Error: What It Is and How to Fix It

Aug 15, 2022 8:03:00 AM |
404 Not Found Error: What It Is and How to Fix It

An in-depth explanation of what a 404 Not Found Error response code is, including tips to help you resolve this error in your own application.

The 404 Not Found Error is an HTTP response status code, which indicates that the requested resource could not be found. Like most HTTP response codes, the cause of a 404 Not Found Error can be challenging to track down and resolve. 

This article will explore the 404 Not Found Error by examining what might cause this error. Later on, we’ll provide a few tips to diagnose and debug your application’s 404 error. 

With that, let’s get started!

Server- or Client-Side?

All HTTP response status codes in the 4xx category are client error responses. These types of messages contrast with errors in the 5xx category, such as the 502 Bad Gateway Error, which are server error responses. 

That said, the appearance of a HTTP 404 error doesn’t always mean the issue is client-related (web browser or device used to access the application). Sometimes, the root of the problem is server-side. Remember, the server is still the network object producing the 404 Not Found Error.

We’ll explore some of the scenarios (and potential solutions) where the error results from the server and/or client issues in the following sections.

Start With a Thorough Application Backup

Make a backup of your application, database, etc. before trying to fix or change the system. Even better, if you have the capability, create a complete copy of the application onto a secondary staging server that isn’t available to the public. This will give you a clean testing ground to test all potential fixes without threatening your live application. 

After you’ve done that, it’s time to start diagnosing and fixing your 404 error.

Diagnosing a 404 Not Found Error

A HTTP 404 error happens when a resource is unavailable. The client (web browser) received a message from the server (remote computer) that the specific resource (web page/URL) is unavailable.

Here are a few scenarios where this could happen: 

  • The client sent a proper request to the server, and the server successfully received that request, and the server could not find a valid resource at that particular location. This is typically due to an invalid URL specified by the client. This represents the majority of 404 Not Found Errors.
  • Some web applications «fake» 404 Not Found Errors when requesting an invalid resource. The server returns a standard 200 OK response code, which means the resource loaded as expected, however, the server displayed a custom «404 page.” Such fake errors are typically referred to as soft 404 errors. 

The provided URL could have been valid in the past, but the server has failed to provide a server-side redirect.

Troubleshooting on the Client-Side

The best way to start troubleshooting a 404 Not Found Error is to look for potential issues on the client side. Here are a few tips to try on the browser or device that’s giving you problems.

Check the Requested URL

The most common cause of a 404 Not Found Error is inputting an incorrect URL. Domain names (e.g., airbrake.io) are case-insensitive, meaning that this mixed case link to AirBrAKe.IO works just as well as the standard, lowercase version of airbrake.io. However, path, query, or fragment portions that appear after the domain name are often case-sensitive unless the application/server configuration pre-processes all URLs as lowercase before execution.

For example, while airbrake.io can be upper, lower, or mixed case, a link to airbrake.io/ERROR-MONITORING/ (with BLOG in uppercase) is invalid, resulting in our good friend the 404 Not Found Error. 

Of course, the lowercase version to https://www.airbrake.io/error-monitoring works just fine, as expected.

As you can see, a minor typo in part of the URL can easily result in an unexpected 404 Not Found Error.

Clear Relevant Cookies

As you may already be aware, HTTP cookies are tiny pieces of data stored on your local device. Websites and applications use these cookies to «remember» information about this particular browser and/or device. 

Most modern web apps take advantage of cookies to store user and browser-specific data. By doing so, the app can identify the client and allow future visits to be faster and easier.

However, cookies can store just about any information. In many cases, web applications or services — such as ad networks — will use data retrieved from local cookies to redirect or handle incoming requests. An invalid or corrupted cookie can «confuse» the server as you try to access a resource that no longer exists. .

In most cases, you only need to concern yourself with cookies relevant to the website or application causing the problem. Cookies are stored based on the web application’s domain name, so you can explicitly remove only those cookies that match the website domain (e.g., airbrake.io). 

However, if you are unfamiliar with manually removing certain cookies, it’s much easier and safer to clear all cookies at once.

Clearing cookies can be accomplished in different ways, depending on the browser you’re using:

  • Google Chrome
  • Internet Explorer
  • Microsoft Edge
  • Mozilla Firefox
  • Safari

Log Out and Log In

If your application has some form of user authentication, the last client-side step to try is to log out and then log back in. 

If you’ve recently cleared the browser cookies, this should usually log you out automatically the next time you try to load the page. 

The application may have a problem with your previous session in some situations. As with other data, the session token (or session string) is stored locally on your device in the cookies and is transferred by the client to the server during every request. If the server doesn’t recognize the session token sent by the client or something has gone wrong with the server that indicates that particular token is invalid, you may get a 404 error.

For most web applications, logging out and logging back in will force the local session token to be recreated.

Debugging Common Platforms

If you’re running common software packages on the server that is responding with the 404 Not Found Error, you may want to start by looking into the stability and functionality of those platforms first. 

The most common content management systems — like WordPress, Joomla!, and Drupal — are all typically well-tested out of the box. Still, once you start modifying the underlying extensions or PHP code, it’s easy to cause an unforeseen issue that results in a HTTP 404 error.

Here are a few tips to help you troubleshoot some of these popular software platforms:

Rollback Recent Upgrades

If you recently updated the content management system itself before the 404 Not Found Error appeared, consider rolling back to the previous version you had installed when things were working fine. 

Similarly, any extensions or modules you may have recently upgraded can cause server-side issues, so reverting to previous versions of those may also help. 

For assistance with this task, simply Google «downgrade [PLATFORM_NAME]» and follow along. In some cases, however, certain CMSs don’t provide a version downgrade capability. This is typically the case for the more popular platforms.

Uninstall New Extensions, Modules, or Plugins

The purpose of new extensions, modules, or plugins (they all mean the same thing) is to improve the capabilities and features of the platform beyond what it’s capable of out of the box. 

Keep in mind that some extensions can take complete control of the system. Once they do, they can make virtually any changes to the PHP code, HTML, CSS, JavaScript, or database. As such, it may be wise to uninstall any recently added extensions if you’re experiencing a 404 error.

Check for Unexpected Database Changes

If you uninstall an extension, it may not completely remove all changes made by the extension. This is particularly true for many WordPress extensions, which are given carte blanche within the application. This can include full access rights to the database. 

These extensions can modify database records that don’t «belong» to the extension itself but are created and managed by other extensions (or even the base CMS itself). In those scenarios, the extension may not know how to revert alterations to database records, so it will ignore such things when uninstalled. 

If you’re convinced an extension is the likely culprit for the 404 Not Found Error, open the database and manually look through tables and records that were likely modified by the extension.

Troubleshooting on the Server-Side

If you aren’t running a CMS application, here are some additional tips to help you troubleshoot your server.

Check Your Web Server Configuration

Most modern web servers provide one or more configuration files that allow you to adjust server behavior based on various circumstances easily. 

For example, the server may be configured to reject requests to specific directories or URLs, resulting in a 404 Not Found Error.

Configuration options for each different type of web server can vary dramatically. We’ll list a few popular web servers you can look through:

  • Apache
  • Nginx
  • IIS
  • Node.js
  • Apache Tomcat

Look Through the Logs

Nearly every web application will keep some form of server-side logs. Application logs are typically the history of what the application did, including requested pages, connected servers, database results, etc.  

Server logs are related to the actual hardware running the application. These logs will often provide details about the health and status of all connected services or the server itself. 

Google «logs [PLATFORM_NAME]» if you’re using a CMS, or «logs [PROGRAMMING_LANGUAGE]» and «logs [OPERATING_SYSTEM]» to get more information on finding the logs in question.

Validate Application Links

There are several tools you can use to ensure your application is not producing any 404 Not Found Errors. 

For starters, you should register your site with the Google Search Console (if you haven’t done so already). This tool gives you insight into what Google’s web crawler bots have found while traversing your site. 

Any issues will be displayed here for all your registered applications and can be an easy (and automatic) way to find invalid links or other site problems.

Need to check a particular resource or URL? Use the W3C Link Checker tool to check links for 404 errors.

Debug Your Application Code or Scripts

If all else fails, it may be that a problem in some custom code within your application is causing the issue. Try to diagnose where the issue may come from by manually debugging your application and parsing through application and server logs. 

Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process. This will allow you to recreate and view when and how the 404 error occurred.

Undoubtedly WordPress is awesome, but your single mistake can make it worse. If you will do anything wrong you may run in problems. Some of them may drive you crazy like WordPress 404 not found is also one of them.

Wordpress page and post 404 not found error

This error means that the client-side which is your, or your website visitor’s web browser, is able to successfully connect to the website’s server, but it is not able to find the actual resource, page or file that was requested.

What is 404, Not Found Error

404 not found error means that the server has not found anything matching the Request uniform resource identifier also known as URI.  Also, there is no indication of the given error if it is temporary or permanent. This ( the requested URI) may be available in the future if requested by the client. Here you can see a list of all http error codes.

404 Not Found Error Message Types

So till now, you have got an understanding of what a 404 message is. 404 is a common message, But generally, it represents different error messages because of different browsers and different servers. Here are some of the different name variations-

404 Error
404 File or Directory Not Found
404 Not Found
404 Page Not Found
Error 404 Not Found
HTTP 404 Not Found
HTTP Error 404
Not Found
Page Not Found
The page cannot be found
The requested URL /~ was not found on this server. That’s all we know.
The requested URL [URL] was not found on this server
We can’t find the page you’re looking for.

404 not found error in WordPress

In WordPress, we generally encounter the “404 not found” error on the front end, which means while accessing your website or blog. On the backend, everything works fine and will not show any error. Most of the time new users think that all the posts and pages are gone now. Because all the WordPress posts and pages will show 404 not found error. So no need to worry about all the data, posts, pages and images, these are still there.

How to fix WordPress Page and Post 404 not found Error

When your blog working fine on the backend and showing a 404 error on the front end, it means there is something wrong with the front end posts and pages. Generally, the Home page of your website will work fine in this case and other pages and posts of your WordPress blog will show the not found 404 error. You can fix this issue by using 2 methods.

But hold on the First Step First– If this is your site make sure you are accessing the right website address. Do not manually write the site page links, always follow them from your dashboard area. As an example, the link of this post is https://apanwar.com/wordpress-404-not-found/ and in the browser address bar, I write it https://apanwar.com/wordpress-404-not-foun/ or deleted the “d” accidentally. Now it will turn to a 404 not found. So you should be careful.

1. Fixing 404 not found by accessing the WordPress admin dashboard

You can fix it by simply saving the Permalinks in your WordPress dashboard. To do this you should navigate to

WordPress Dashboard ->Settings -> Permalinks and then click on the “Save Changes” button.

You have no need to make any changes there, just go there and hit the Save button. Most of the time this solves the 404 not found page issues in WordPress. But if this still not solved, there are chances that your .htaccess file is write-protected.

2. Fixing 404 not found by using cPanel or FTP

If the earlier step does not solve the issue, then you should add the code manually to .htaccess file. To do this you should have access to FTP or cPanel. Login to your cPanel and open FileManager or using FTP login to your server with given details( you can ask your hosting provider for these details). You should also use an FTP client like Filezilla to access server files. It is free software. After login locate the .htacess file.

This file will be in your root location of WordPress installation you will also see the wp-includes and wp-content folders there. Note that .htaccess is a hidden file and if this is not visible there you should make visible the hidden file. If you are still not able to see the .htaccess file, Simply create it and write the given code to this file

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

After saving the .htaccess file, open and reload the site you can also try Ctrl + F5.

How to Fix 404 not found Error on WordPress Admin Dashboard Area

You can also face this error while accessing your wordpress dashboard area. Here are the solutions if you stuck in this situation and not able to access your WordPress admin dashboard.

1. Edit wp-config.php file

If you see this notification 404 Not found The requested URL  . . . was not found on this server. Generally, this error encounter after moving a WordPress site from one server to another, subdomain to domain, localhost to live site or when you change your domain name.

    Explore More

  • Know How To Fix White Screen Of Death In WordPress
  • How To Solve Fatal Error Allowed Memory Size Of 1234567 Bytes Exhausted?
  • How to Fix: Error Establishing Database Connection in WordPress
  • How to Fix Connection Timed Out In WordPress Site
  • How To Fix Internal Server Error 500 In WordPress Full Step By Step Guide!
  • How To Fix Warning: Cannot Modify Header Information Error In WordPress!

I assume you do not have access to the WordPress admin dashboard, because when you try to access dashboard it shows you this message The requested URL  . . . was not found on this server. So you should have access to the server via FTP or cPanel to edit wp-config.php file. it will be in your root location, where you can also see wp-content and wp-includes folders.  Edit wp-config.php file and add this code:

define('WP_HOME','yoursitename');
define('WP_SITEURL','yoursitename');

Please note that you should replace “yoursitename” with your actual site name. In my case, the site name will be https://apanwar.com

2. Editing .htaccess file to fix 404 error on WordPress admin dashboard

If you face The requested URL [ any url] was not found on this server. You should add the given below content to your .htaccess file. The instructions already are given about this file.

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

3. Checking Security plugin to fix WordPress dashboard 404

You may accidentally disable the wp-admin URL by using security plugins. Most of the security plugin changed the default wp-admin and wp-login.php links so that no one can assume your login URL. And when you will try to access your dashboard by writing wp-admin or wp-login.php at the end of your site name, it will show you the not found error.

So you should check if you have recently installed any security plugin. Check its configuration if you have already opened the admin area.  If not you should access the server by using FTP or cPanel and rename the security plugin folder. It will be located at/public_html/wp-content/plugins/, here you have to find the plugins folder name. it may be itheme security or wordfence or any other plugin. After renaming the plugin folder, the respective plugin will get disabled and you can try again to access the wp-admin and it will work now. Some time misconfiguration of security plugin can also lead to Sorry you are not allowed to access this page error.

4. Check https and http in the database

Check your database by using phpMyAdmin. Open wp_options table and check for site URL, in sitteurl it may be set to “HTTPS” instead of just “HTTP”. Change it and try to access your site with wp-admin again. It will work now.

This generally happened when websites migrated from one host to another host or doing a live site from the localhost.

5. Check Plugin or theme conflict to fix admin dashboard 404 error

You may also face 404 not found for the wp-admin area due to themes or plugins conflict. So you should access the server by cPanel or FTP and try renaming the plugins one by one and check the wp-admin area if working.  If you still facing the issue it means your theme may be also faulty. So simply activate any default WordPress theme. Sometimes old or outdated WordPress themes do not work properly with all plugins and even with WordPress core too so you should check it by disabling them.

I hope the steps given above will help you solve WordPress 404 not found issue. You can fix it by using the WordPress dashboard or by accessing FTP or cPanel. If you do not have access to the WordPress dashboard or if this is not working for any reasons then you should use the second method by accessing the server files.

I will be more than happy when you will let me know if this is a real help for you and which option works best for you.

I am trying to make my app connecting to pusher on a private channel.

But I am getting the following error in console:

POST http://localhost/broadcasting/auth 404 (Not Found) Pusher : Couldn’t retrieve authentication info. 404Clients must be authenticated to join private or presence channels

ChatEvent.php

<?php

namespace AppEvents;

use AppUser;

use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;

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


   public $message;
   public $user;



    public function __construct($message, User $user)
    {

       $this ->message = $message;

        $this ->user = $user;


    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('chat');
    }
}

App.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

import Vue from 'vue'
import VueChatScroll from 'vue-chat-scroll'
Vue.use(VueChatScroll)

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example', require('./components/Example.vue'));

Vue.component('chat-message', require('./components/ChatMessage.vue'));


const app = new Vue({
    el: '#app',

   data:{ 

    message:'',

     chat:{     

        message:[]

     } 

      },

   methods: {  send() { 

if(this.message.length !=0)
{

    this.chat.message.push(this.message);

    this.message= '';

}
   } },


   mounted()

   {

       Echo.private('chat')
    .listen('ChatEvent', (e) => {
        console.log(e.order.name);
    });

   } 

});

channels.php

<?php



Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});


Broadcast::channel('chat', function() {

return true;

});

ChatController.php

<?php

namespace AppHttpControllers;

use AppEventsChatEvent;
Use AppUser;
use IlluminateSupportFacadesAuth;
use IlluminateHttpRequest;

class ChatController extends Controller
{


  public function __construct()

    {
        $this->middleware('auth');
    }


  public function chat()


  {

 return view('chat');

}


//public function send(Request $request)

//{

 // $user = User::find(Auth::id());

 // event(new ChatEvent($request -> $message, $user));

//}


public function send()

{

    $message = "Hello";

  $user = User::find(Auth::id());

  event(new ChatEvent( $message, $user));

}

}

bootstrap.js

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

    require('bootstrap-sass');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from 'laravel-echo'

 window.Pusher = require('pusher-js');

 window.Echo = new Echo({
     broadcaster: 'pusher',
     key: '815bcd2378a647ffaad7',
      cluster: 'ap2',
    encrypted: false
 });

what may be the cause for this error? any solution

Понравилась статья? Поделить с друзьями:
  • Positional argument follows keyword argument python ошибка
  • Posiflex pp 6900 ошибка печати
  • Porte avg ouverte ошибка citroen c4
  • Portal knights ошибка при запуске
  • Portal knights ошибка на непонятном языке