简体   繁体   中英

Cannot Read Property Undefined

I have created an endpoint in my .NET Core MVC project.

My Api is:

[HttpGet("/api/notifications")]
public async Task<IActionResult> Notifications()
{
      var user = await GetCurrentUserAsync(); // Gets the current logged user.

      if (user == null)
            return StatusCode(401);

      var notifications = _notificationService.GetUserNotifications(user.Id);

      var serialized = JsonConvert.SerializeObject(notifications);

      return Ok(serialized);
}

And I'm using SignalR for Database Change Notifications

[HttpPost]
public async Task<IActionResult> CreateNotification(NotificationModel model)
{
    var notification = new Notification()
    {
          NotificationTitle = model.NotificationTitle,
          NotificationBody = model.NotificationBody,
          DateTime = DateTime.UtcNow
    };

    _notificationService.Create(notification);

    // Many to many relationship between Notifications and Users
    // Many to Many table looks like => NotificationId | UserId | isRead
    // So in this action, because of the notification is created for the first time, 
    // NotifyUsers method will set 'isRead' property to false.
    _notificationService.NotifyUsers(notification, model.userIds);

    //Here Notify the Clients with SignalR!
    await _notificationHubContext.Clients.All.SendAsync("initSignal", "message");

    return RedirectToAction("PublishedNotification", "Portal");

 }

and at last, I have a Javascript file where I'm controlling the data comes from api with SignalR.

notification.js

window.onload = () => notifyUser();

var connection = new signalR.HubConnectionBuilder().withUrl("/NotificationHub").build();

connection.on("initSignal", () => notifyUser());

connection.start().catch(function (err) {
    return console.error(err.toString());
});

const endPoint = "http://{my-site}.com/api/notifications";

async function getNotifications() {
    try {
        var response = await fetch(endPoint);

        var notifications = await response.json();

        // Filters notifications where isRead properties are "false"
        var unreadNotifications = notifications.filter(notification => !notification.isRead);

        return { notifications, unreadNotifications };
    } catch (e) {
        console.error(e);
    }
}

function notifyUser() {
    var ul = document.getElementById("notification-list");
    ul.innerHTML = "";
    var notificationDropdownBtn = document.getElementById("notification-dropdown");    
    var initialNotificationLimit = 2;

    notificationDropdownBtn.onclick = () => {
        notifyUser();
    }

    getNotifications().then(notifications => {
        let { unreadNotifications = [] } = notifications;

        if (unreadNotifications.length > 0) {

            var notificationControl = document.getElementById("notification-control");

            notificationControl.textContent = unreadNotifications.length;

            unreadNotifications.forEach((notification, index) => {
                if (index > initialNotificationLimit) {
                    return;
                }
                ul.insertAdjacentHTML("beforeend", (createNotificationListItem(notification)));                
            });

            var loadBtn = document.getElementById("load-more");
            loadBtn.onclick = () => {
                ul.innerHTML = "";
                initialNotificationLimit += 3;
                unreadNotifications.slice(0, initialNotificationLimit).forEach(notification =>
                    ul.insertAdjacentHTML("beforeend", (createNotificationListItem(notification))));
            }

        } else {
            ul.insertAdjacentHTML("beforeend", "<span class='text-muted'>You don't have any unread notifications!</span>");
        }
    });
}

function createNotificationListItem(notification) {
    var { NotificationId, NotificationBody, NotificationTitle, DateTime } = notification.Notification;

    return `<li class="media">
                <div class="mr-3 position-relative">
                    <img src="" width="36" height="36" class="rounded-circle" alt="">
                </div>
                <div class="media-body">
                    <div class="media-title">

                       //In this route, which goes to my Announcement Action in my .NET Core,
                       // which will set isRead property to "True"
                        <a href="/announcement/${NotificationId}">
                            <span class="font-weight-semibold">${NotificationTitle}</span>
                            <span class="text-muted float-right font-size-sm">${DateTime}</span>
                        </a>
                    </div>
                    <span class="text-muted">${NotificationBody.substring(0, 25)}...</span>
                </div>
            </li>`
}

Ok, so this is my projects notifications part.

**ERROR / PROBLEMS **

When I published my site with FTP, a Console error appeared.

But the main problem is, till my friend told me that there is an error with notifications, and a console error, I didnt actually know that there was an error. Because on my computer everything was working, and I tried on another friends computer, and also working, but the others told me that on their computer, they got this error.

Error was,

Cannot read property undefined  'unreadNotifications'  => notification.js

I tried to told them to remove browser cache history, for some of them it worked, and for some of them it didn't..

I really got stuck in here, I don't know how to google it...

NOTE: For your information, my endpoint has the data, and my actions or my ef methods are all working fine...

How can a code works differently in other computers, and also I didn't know how to Google this problem, and as you can understand I'm not an expert...

NOTE: Last thing my Cors setup is:

services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
       builder.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
}));

EDIT : I've tried to log in as the same user on different computers, as I've mentioned above, when I type "http://{my-site}/api/notifications", on my computer and some others , I got the JSON object (3 notifications so far.), but on the other computers this endpoint return an empty array => []

Second EDIT : When I debugged my js file on browser, this is my response, it cant access the cookies which are set to HttpOnly , I tried to fetch with credentials:same-origin , didn't actually worked.

response = Response {type: "cors", url: "{mysite}.com/account/login?ReturnUrl=%2Fapi%2Fnotifications", redirected: true, status: 200, ok: true, …}

If unread notifications are only required to display just return that from your getNotifications() method

async function getNotifications() {
    try {
        ...
        var unreadNotifications = notifications.filter(notification => !notification.isRead);
        return unreadNotifications;
    } catch (e) {
        console.error(e);
    }
}

And in notifyUser() use it as

getNotifications().then(unreadNotifications => {
    if (unreadNotifications.length > 0) {
        ...
    }

It is solved with AJAX,

The Error was my fetch API from js file, couldn't reach my "Cookies" and return

options.AccessDeniedPath = "/account/accessdenied"; under

services.ConfigureApplicationCookie .

When I debugged my notification.js response object was

response = Response {type: "cors", url: "{mysite}.com/account/login?ReturnUrl=%2Fapi%2Fnotifications", redirected: true, status: 200, ok: true, …}

If you set your Cookies to HttpOnly=true then you are making them unreachable from client side scripts.

So, I've made an Ajax call directly under my .cshtml in a script tag and my Ajax call was:

function notifyUser() {
        var ul = document.getElementById("notification-list");
        ul.innerHTML = "";
        var notificationDropdownBtn = document.getElementById("notification-dropdown");
        var initialNotificationLimit = 2;

        notificationDropdownBtn.onclick = () => {
            notifyUser();
        }

        $.ajax({
            type: "GET",    

            //In here I directly use my controller and action.        
            url: "@Url.Action("Notifications", "Portal")",
            contentType: "application/json",
            dataType: "json",
            success: function (notifications) {

            var unreadNotifications = notifications.filter(notification => !notification.isRead);

            if (unreadNotifications.length > 0) {
                ...
            } else {
                ...
            },
            error: function (req, status, error) {
                console.error(error);
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM