简体   繁体   English

无法读取未定义的属性

[英]Cannot Read Property Undefined

I have created an endpoint in my .NET Core MVC project.我在我的 .NET Core MVC 项目中创建了一个端点。

My Api is:我的 API 是:

[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我正在使用 SignalR 进行数据库更改通知

[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.最后,我有一个 Javascript 文件,我在其中使用 SignalR 控制来自 api 的数据。

notification.js通知.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.当我使用 FTP发布我的网站时,出现控制台错误。

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...注意:供您参考,我的端点有数据,我的操作或我的 ef 方法都工作正常......

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...代码在其他计算机上的工作方式如何不同,而且我也不知道如何在Google 上搜索此问题,正如您所了解的,我不是专家...

NOTE: Last thing my Cors setup is:注意:我的 Cors 设置的最后一件事是:

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 => []编辑:正如我上面提到的,当我在我的计算机和其他一些计算机上键入“http://{my-site}/api/notifications”时,我尝试在不同的计算机上以同一用户身份登录,我得到了 JSON 对象(到目前为止 3 个通知。),但在其他计算机上,此端点返回一个空数组 => []

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.第二次编辑:当我在浏览器上调试我的 js 文件时,这是我的响应,它无法访问设置为HttpOnlycookie ,我尝试使用credentials:same-origin ,但实际上没有工作。

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如果仅需要显示未读通知,则只需从getNotifications()方法返回该通知

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

And in notifyUser() use it as并在notifyUser()其用作

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

It is solved with AJAX,用AJAX解决了,

The Error was my fetch API from js file, couldn't reach my "Cookies" and return错误是我从js文件中获取 API,无法访问我的“Cookies”并返回

options.AccessDeniedPath = "/account/accessdenied"; under在下面

services.ConfigureApplicationCookie . services.ConfigureApplicationCookie

When I debugged my notification.js response object was当我调试我的notification.js response对象是

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.如果您将Cookie设置为HttpOnly=true,那么您将无法从客户端脚本访问它们。

So, I've made an Ajax call directly under my .cshtml in a script tag and my Ajax call was:因此,我直接在script标记中的.cshtml下进行了 Ajax 调用,我的 Ajax 调用是:

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);
            }
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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