Ошибка value is not an object

I am using loopback in backend. I am getting this error

    Unhandled error for request POST /api/meetups/auth: Error: Value is not an object.
        at errorNotAnObject (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:80:13)
        at Object.validate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:51:14)
        at Object.fromTypedValue (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:14:22)
        at Object.fromSloppyValue (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/types/object.js:41:17)
        at HttpContext.buildArgs (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:193:22)
        at new HttpContext (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:59:20)
        at restStaticMethodHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/rest-adapter.js:457:15)
        at Layer.handle [as handle_request] (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/layer.js:95:5)
        at next (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/route.js:137:13)
        at Route.dispatch (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/route.js:112:3)
        at Layer.handle [as handle_request] (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/layer.js:95:5)
        at /Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:281:22
        at Function.process_params (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:335:12)
        at next (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:275:10)
        at Function.handle 
(/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:174:3)
        at router (/Users/ankursharma/Documents/projects/meetupz/node_modules/express/lib/router/index.js:47:12)

I have already searched stackoverflow, but I didnt find answer. Basically, i was trying to use body-parser . I went through one of the stackoverflow thread and implemented its solution. I was able to use body-parser successfully. So, that error has been solved. But, now this error is giving me tough time.

server.js file

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var bodyParser = require('body-parser');
var multer = require('multer');

var app = module.exports = loopback();

//code for body parsing
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//app.use(multer()); // for parsing multipart/form-data

//code for body parsing ends

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(//$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

In middleware.json, I have updated parse property as well

"parse": {"body-parser#json": {},
    "body-parser#urlencoded": {"params": { "extended": true }}},

For some reason, that error has gone. Not sure, may be it will come again. But now, this is the error, I am seeing

Unhandled error for request POST /api/meetups/auth: TypeError: cb is not a function
    at Function.Meetups.auth (/Users/ankursharma/Documents/projects/meetupz/common/models/meetups.js:117:3)
    at SharedMethod.invoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/shared-method.js:270:25)
    at HttpContext.invoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/http-context.js:297:12)
    at phaseInvoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:677:9)
    at runHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:135:5)
    at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
    at Object.async.eachSeries (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:162:9)
    at runHandlers (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:144:13)
    at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)
    at /Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:157:25
    at /Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:154:25
    at execStack (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:522:7)
    at RemoteObjects.execHooks (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:526:10)
    at phaseBeforeInvoke (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/lib/remote-objects.js:673:10)
    at runHandler (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/lib/phase.js:135:5)
    at iterate (/Users/ankursharma/Documents/projects/meetupz/node_modules/strong-remoting/node_modules/loopback-phase/node_modules/async/lib/async.js:146:13)

[REQUIRED] Step 2: Describe your environment

  • Operating System version: MongoDB Atlas Trigger (Realm App)
  • Firebase SDK version: 11.4.1
  • Firebase Product: messaging
  • JS SDK Version: 3.18.0
  • NPM version: I don’t know

[REQUIRED] Step 3: Describe the problem

Executing admin.messaging().sendMulticast(message) returns an error and is not working anymore after upgrading to firebase-admin: 11.4.1 from 11.0.1 and with the release of fastify/busboy 1.2.0 :

uncaught promise rejection: TypeError: Value is not an object: undefined

The difference with my previous issue #1902 is that now messaging().sendMulticat(message) is crashing and no longer deliver the push notification.

Steps to reproduce:

  1. Create a MongoDB Atlas trigger
  2. Add firebase-admin as external dependency and make sure it’s 11.4.1
  3. Add the service-account.json as a value
  4. Run the code with the below code

Relevant Code:

exports = async function() {

  const admin = require("firebase-admin");
  const json_creds = context.values.get("service_account_value_name");
  	  
    const title = "Test";
    const body = "This is a test";
   
    const message= {
      android: {
        notification: {
          title: title,
          sound: "default",
          body: body,
        },
      },
      apns: {
        payload: {
          aps: {
            alert: {
              title: title,
              body: body,
            },
            mutableContent: 1,
            contentAvailable: 1
          }
        },
      },
      tokens: ["device_token_1", "device_token_2"]
    };
    	
    admin.initializeApp({
        credential: admin.credential.cert(JSON.parse(json_creds))
      });
  
    admin.messaging().sendMulticast(message);

    console.log("Messages sent !");
  }
}

Forum

How do I…?

Hello,

I’d like to use JQuery for calculating the padding-right for some td. It works in a browser, but not in Princexml. After some research, I discovered, that the problem can be reduced to this code:

$('td.centeredright16').each(function(){
$(this).width();
});

The problem is this line $(this).width();. The error message is

prince: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js:2: error: TypeError: value is not an object

I changed the code to see what’s going on

$('td.centeredright16').each(function(){
  console.log(typeof($(this)));
  console.log($(this).width());
})

and the error message is a little bit confusing:

object
prince: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js:2: error: TypeError: value is not an object
object
prince: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js:2: error: TypeError: value is not an object

$(this) is an object, but I get a TypeError, because it’s not an object…?!?

Soo.. What’s the problem?

Kind regards,
chops

Prince does not support the jQuery width() and height() methods. More generally, JavaScript is run before typesetting, so you cannot interrogate element positions and dimensions and then make changes. There is no layout reflow like in a browser.

Then what is the usefulness of JavaScript in PrinceXML?

It can be used to do structural transformations of the input document, eg. generating a table of contents or index, defining new counter styles, generating charts or graphs using SVG or the <canvas> element. It just can’t do anything that depends on the result of typesetting the document. Not yet, anyway. :)

Thanks mikeday.
Do you have any example usage of JavaScript?

I have tried to change innerHTML using jQuery and its not working. Seems to be that PrinceXML doesn’t work with document.ready

You can use onload or DOMContentLoaded events. Not sure why $(document).ready doesn’t work though, presumably it uses a similar event mechanism.

I’d like to move certain elements to the end of the document but am getting the TypeError: undefined value is not an object. From your comments above, I’m wondering if this kind of structural change is not supported?

Specifically, something like this:

<script type="text/javascript">
  function moveGraphics() {
    var pageNode = document.getElementById('page');
    var graphicsList = document.getElementsByTagName("div");
    for (i = 0; i < graphicsList.length; i++) {
      if (graphicsList[i].classList.contains('graphicWrapper')) {
        pageNode.appendChild(graphicsList[i]);
      }
    }
  }
</script>

I’m spotting a couple of issues here.

1. Prince does not support classList

Prince does not support classList, probably because it’s not part of a W3C web standard, inclusion in the WhatWG standard notwithstanding. With the code you’ve provided, I recommend using a regular expression matched against an element’s className property instead, e.g.

element.className.match(/(^|s)graphicWrapper($|s)/)

If the question of whether a graphicWrapper is a div or a span is not important, then an alternate approach is to use document.getElementsByClassName(«graphicWrapper») to get the list of elements to shunt to the end. If on the other hand it is important to consider the element type, then you can (and probably should) use document.querySelectorAll(«div.graphicWrapper»). This approach has the additional benefit (in the context of your code) of NOT updating its NodeList live, as described in my next point.

2. The NodeList returned by getElementsByTagName updates itself dynamically

document.getElementsByTagName returns a NodeList which is updated «live», which is to say it changes as the DOM does. Because you’re looping through a list from the beginning while simultaneously mutating it at the end, that will produce unexpected results. In your specific case I would recommend iterating backwards, e.g.

for (i = graphicsList.length - 1; i >= 0; i--) { /* ... */ }

Depending on the structure of your document, your code might also work if instead of making the change above you decremented i every time you removed an element from the NodeList or pushed it to the end, e.g.

pageNode.appendChild(graphicsList[i--]);

That may prove to be brittle however. One final option is to convert the NodeList to an array before iterating through it, e.g.:

var graphicsList = [].slice.call(document.getElementsByTagName("div"));

Here’s a simple demonstration of the live updating behaviour of getElementsByTagName:

<article>
  <div></div>
  <div></div>
  <div></div>
</article>

<script>

  // 1. select divs in article
  var divs = document.querySelector("article").getElementsByTagName("div");
  // 2. log how many (result = 3)
  Log.data("number of divs selected", divs.length);
  // 3. remove the first div
  divs[0].parentNode.removeChild(divs[0]);
  // 4. log how many (result = 2)
  Log.data("number of divs selected", divs.length)

</script>
</body>

That little example should give you a pretty good idea of why iterating through NodeLists from beginning to end rather than the inverse is so fraught with errors.

Hello textninja,

Thanks for the reply, that was very helpful. My only issue is that iterating in reverse order ends up putting my images into the document in reverse order since appendChild always appends to the end. I tried iterating in order though and I see why you said not to do that as it did indeed create quite the mess. I’m not that familiar with javascript but I’ll look for a different way to do the appends in reverse that works. Thanks again!

No problem, and insertBefore is probably the function you’re looking for. For example, given a new element and a container, to insert the new element to the start of the container you can use code like the following:

container.insertBefore(newElement, container.firstChild);

It’s referencing the container’s first child element, which may not exist, but the code will work regardless as it falls back to append in such instances.

The JavaScript error TypeError: null is not an object occurs when a property is accessed or a method is called on a null value. This specific error message is shown only on Safari. Other browsers display a different message for this error.

Error message:

TypeError: null is not an object (evaluating 'x.y') - Safari
TypeError: Cannot read properties of null (reading 'x') - Chrome
TypeError: x is null - Firefox

Error Type:

TypeError

What Causes TypeError: Null is Not an Object

The TypeError: null is not an object occurs when a property is read (or set) or a method is called on a null value. An object was expected in code but was not provided. Since null is not an object in JavaScript, using a null value when an object is expected does not work. A proper object must be provided in such situations.

TypeError: Null is Not an Object Example

Here’s an example of a TypeError: null is not an object thrown when trying to read a property of a null value:

var a = null;
console.log(a.b);

In the above code, the variable a has a null value. When the property b is attempted to be read on it, a TypeError: null is not an object is thrown:

TypeError: null is not an object (evaluating 'a.b')

How to Fix TypeError: Null is Not an Object

When such an error occurs, it means that a null value was provided where an object was expected. It should be ensured that the variable causing the error does not have a null value and is a proper object.

To avoid coming across situations where properties of null variables may be accessed accidentally, an if check should be added before dealing with such variables:

if (myVar !== null) {
    ...
}

Updating the previous example to include an if check:

var a = null;
if (a !== null) {
    console.log(a.b);
}

Running the above code avoids the error since the property b is only accessed if a is not null.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Javascript errors easier than ever. Sign Up Today!

Ситуация: вы пишете скрипт, в котором вам нужно выяснить расстояние от верха экрана до начала нужного элемента. У этого элемента есть класс .entry-content, и вы используете jQuery, чтобы достучаться до него:

// …
var dh;
dh = $('.entry_content').offset().top;

После запуска скрипта браузер выдаёт ошибку:

❌ TypeError: ‘undefined’ is not an object

Странно, но вы точно знаете, что таким способом можно искать элемент по его классу. Более того, точно такой же код работает тремя строчками выше и без ошибок.

Что это значит: браузер при виде точки понимает, что перед ним — объект, у которого есть какие-то свойства. Эта ошибка означает, что вы пытаетесь обратиться к свойствам несуществующего объекта.

Когда встречается: когда программист делает опечатки в имени объекта, неправильно объявляет его или начинает работать с чем-то, что точно не объект.

В нашем примере программист неправильно указал имя раздела при вызове, и вот что произошло:

  1. Браузер знает, что на странице есть элемент с классом entry-content, который написан через дефис.
  2. Программист увлёкся и поставил знак подчёркивания вместо дефиса.
  3. Скрипт попытался найти этот класс, но не смог, поэтому вернул значение undefined.
  4. После этого команда стала выглядеть так: dh = undefined.offset().top, но undefined.offset() — это не объект, а что-то неопределённое, у которого нет свойства top.
  5. Браузер выдаёт ошибку, что вообще-то это не объект и работать с ним он не будет.

Что делать с ошибкой TypeError: ‘undefined’ is not an object

Эта ошибка означает, что вы пытаетесь использовать как объект то, что им не является. Чтобы исправить эту ошибку, проверьте:

  • нет ли у вас опечаток в именах и названиях (скорее всего);
  • правильно ли вы определили нужный объект;
  • в jQuery нужно будет дополнительно проверить, не теряется ли значение this или $ при использовании внутри функции;
  • есть ли внутри вашей переменной или объекта вообще что-нибудь, с чем можно работать.

Попробуйте сами

У вас есть страница с элементом <h1 id="text-test"></h1> и JavaScript-кодом. При повторном запуске анимации он падает с нашей ошибкой. Попробуйте выяснить, почему так происходит.

document.addEventListener('DOMContentLoaded', function (event) {
  var dataText = ["Test", "Hello", "Salut", "Bonjour"];
  function typeWriter(text, i, fnCallback) {
    if (i < (text.length)) {
      document.getElementById("text-test").innerHTML = text.substring(0, i + 1) + '<span aria-hidden="true"></span>';
      setTimeout(function () {
        typeWriter(text, i + 1, fnCallback)
      }, 100);
    }
    else if (typeof fnCallback == 'function') {
      setTimeout(fnCallback, 700);
    }
  }
  function StartTextAnimation(i) {
    if (typeof dataText[i] == 'undefined') {
      setTimeout(function () {
        StartTextAnimation(0);
      }, 10000);
    }
    // ВОТ ТУТ ОШИБКА ↓
    if (i < dataText[i].length) {
      typeWriter(dataText[i], 0, function () {
        StartTextAnimation(i + 1);
      });
    }
  }
  StartTextAnimation(0);
});

Понравилась статья? Поделить с друзьями:
  • Ошибка unreal engine 4 crash reporter как исправить
  • Ошибка value if not set перевод
  • Ошибка unreal engine 4 crash reporter satisfactory
  • Ошибка utweb exe как убрать
  • Ошибка valorant код ошибки 29