【问题标题】:Cannot Read Property Undefined无法读取属性未定义
【发布时间】:2020-04-06 05:39:03
【问题描述】:

我在我的 .NET Core MVC 项目中创建了一个端点。

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

我正在将 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");

 }

最后,我有一个 Javascript 文件,我在其中使用 SignalR 控制来自 api 的数据。

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>`
}

好的,这是我的项目通知部分。

**错误/问题**

当我使用 FTP发布我的网站时,出现了控制台错误。

但主要问题是,直到我的朋友告诉我通知有错误和控制台错误,我实际上并不知道有错误。因为在我的电脑上一切正常, 我在另一台朋友的电脑上试了试,也可以工作,但其他人告诉我,在他们的电脑上,他们收到了这个错误。

错误是,

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

我试图告诉他们删除浏览器缓存历史记录,其中一些有效,而另一些则无效..

我真的卡在这里,我不知道如何谷歌它......

注意:供您参考,我的端点有数据,我的操作或我的 ef 方法都工作正常......

代码在其他计算机上的工作方式有何不同,而且我不知道如何Google这个问题,你可以理解我不是专家......

注意:我的 Cors 设置的最后一件事是:

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

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

第二次编辑:当我在浏览器上调试我的 js 文件时,这是我的响应,它无法访问设置为 HttpOnly 的 cookies >,我尝试用credentials:same-origin 获取,实际上没有成功。

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

【问题讨论】:

  • 你想从getNotifications()方法、notifications或unreadNotifications返回什么?
  • 我想要unreadNotifications,我正在向用户展示它们,类似于此页面,导航栏上方的stackoverflows收件箱。
  • 我在上面有一个编辑,你能检查一下吗?

标签: javascript asp.net-mvc api asp.net-core asp.net-web-api


【解决方案1】:

用AJAX解决,

错误是我从 js 文件中获取 API,无法访问我的“Cookie”并返回

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

services.ConfigureApplicationCookie.

当我调试我的 notification.js response 对象时

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

如果您将 Cookies 设置为 HttpOnly=true,那么您将无法从 client 端脚本访问它们。

所以,我直接在 .cshtml 下的 script 标记中进行了 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);
            }
        });
    }

【讨论】:

    【解决方案2】:

    如果只需要显示未读通知,请从您的 getNotifications() 方法中返回它

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

    在notifyUser() 中使用它

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

    【讨论】:

    • 嘿,我试试这个,不幸的是没有任何改变。但我确实在浏览器上进行了调试,我的响应是“未经授权”,我的意思是 /api/notifications 重定向到我的“登录”操作。 response = Response {type: "cors", url: "{mysite}.com/account/login?ReturnUrl=%2Fapi%2Fnotifications", 重定向: true, status: 200, ok: true, ...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多