Programming

Node Error : Promise.all is not a function

Posted on

Are you getting the message?

Promise.all is not a function

At first I was thinking is my node version out of date?

But the answer is actually that your Promise.all function inst receiving an array. 

 

 

SyntaxError: Unexpected token c in JSON at position 1 when you POST JSON data with curl

Posted on Updated on

When trying to use curl to POST data to your api and getting an error?

The error:

SyntaxError: Unexpected token c in JSON at position 1

Answer

You need to wrap your json block in quotes

curl -X POST -H "Content-Type: application/json" -d '{"content":"a"}' your_url_here

“Invalid Host Header” Errors when running your React project off your cloud ide

Posted on

This one was a pain. So your react app is hosted on localhost:3000 and your node backend is on localhost:3001. This isn’t a problem if you a developing locally. You open up your browser and everything connects perfectly. But if you are developing on a cloud ide or vps, you are probably connecting to something like someweirdname.cloudidename.com.

By itself, running npm start will give you your project nicely. But once you have a backend that your browser isnt accessing locally, you might get the dreaded  “Invalid Host Header”

Here is how I fixed my problem:

File: package.json  add the following:  where the value is your ide host name

"proxy": "http://mybackend.mycloudidehost.c9.io"

.env.development.local <- thats DOT ENV DOT DEVELOPMENT DOT LOCAL , I spent a good while troubleshooting because of the missing DOT,  add the following:

DANGEROUSLY_DISABLE_HOST_CHECK=true

The above is not recommended if you are developing locally, but its a cloud ide.

 

Advertisement

Heroku : Application error : error code=H12 desc=”Request timeout” : when using remote database

Posted on Updated on

I was working with a Node application I built, which connected to a hosted MongoDB database. Everything worked perfectly on my development machine. Once I pushed everything to heroku is where I would start getting problems.

I received this error after trying to connect to my apps webpage

Application error

An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command
heroku logs --tail

When checking the logs this error stood out

2019-08-01T18:36:14.968797+00:00 heroku[router]: at=error code=H12 desc=”Request timeout” method=GET path=”/api/notes” host=spongebobs-basin
-47509e646.herokuapp.com request_id=e70f60dc-321d-421c-9c24-6974ba3a79bb fwd=”99.99.99.9″ dyno=web.1 connect=0ms service=30000ms status=503 b
ytes=0 protocol=https

So what are the important things in this line?

  • desc=”Request timeout”
  • method=GET path=”/api/notes”
  • service=30000ms
  • status=503 b

I am connecting to the correct path, using the correct method, but after 30 seconds the server is timing out , so heroku sends a 503 Service Unavailable.

This was a strange one to figure out since locally everything worked great. I changed some things around for testing and found that the application on heroku was not connecting to the remote mongoDB host. Locally it worked great. Was this a herkoku problem?

Solution:

The .env file I used locally required the mongoDB URI to be in quotes. The app would not work without the quotes. But the configuration variables in heroku needed to be added without the quotes.

  • .env  ‘mongodb+srv://username:password@somecluster.mongodb.net/note-app’
  • Config Vars  mongodb+srv://username:password@somecluster.mongodb.net/note-app

Binary Search Tree

Posted on

Binary search tree, also known as an ordered tree, is a phrase that you will see a lot when discussing Computer Science, or looking at leetcode discussions. its a root node, whose leaves and branches on the left are lower in value than the root, and the leaves and branches on the right side are higher than the root. In simple terms, left is less than, right is greater than.

The Binary Search Tree is a data structure that is used for performing lookups. The strength of a BST (Binary search tree) is that when performing a lookup via comparisons, it allows you to drop half the values in the data structure every time you make a comparison. WHen doing this over large data sets this can potentially save a lot of time and searching. The complexity of the BST would be O(log n), where over time as the data set grows, the search timed does so miniscule. Compare this to a linear search algorithm, where we would start at the beginning of the data structure, and iterate over it until we found the value desired. As the data set grows so does the amount of time it takes to go throw that set.

If you aren’t familiar with linked lists, than you should go over that first, because a BST is like a link list on caffeine! When creating a node of a BST, generally, the node will have these properties, a value, a left pointer, and a right pointer. So instead of a next for linked lists, we can traverse the tree by going left or right. Each path that you take is a branch.

The best way to wrap your head around why the binary search tree is the classic phone book example. Let’s say you were looking for Larry King. There is a bookmark for the middle of the phone book. You open it and it has the name Might Mouse. Ok, so King must be to the left of mouse. Anything after Mouse, we can ignore. Now we estimate the middle of A-M which would be around the letter G, so we see that there is a bookmark at G, and we find Garry Golden. Hmm, King would be after Golden, so now we ignore A-G. So from G-M we go to the middle and see a bookmark at J. We turn to J and find Michael Jordan. Hmm, K comes after J so now we look between J-M, and we end up between K and L. Ok so the name we have is John Kzrinsky. Ah, ok it must be to the left. We found Larry King! And that is how a BST would operate.

Hoisting in JavaScript

Posted on Updated on

Hoisting is a term that i thrown around a lot if you are reading up on JavaScript. But what is hoisting? The verb hoist is defined as “an act of raising or lifting something”. So we must be raising something up. But What? Variables and function declarations  are what are hoisted to the top of the code. By verb definition, the variables and function declarations are what are moved to the top of scope. That is how it’s actually been explained to me in many tutorials, videos, and even in various lectures. However, this isn’t actually he case!  “The variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.” [A] So the code isn’t moved, but by declarations being placed in memory, you can call those declarations in your code before they are read later. Meaning, referenced decelerations can be placed under callers in code.

If we look at the code below, we see that the function caller is accessing function toBeHoisted before it’s defined. Thanks to JavaScript’s hoisting, this is not a problem.

function caller(){
  let x = toBeHoisted();
  console.log(x+5);
}

function toBeHoisted(){
  return 5;
}

caller() //10

.What we have to take heed of however is that initializations are NOT hoisted, only definitions. So this is why it is said only functions are hoisted, even though technically, only declarations are hoisted, which can be variables or functions. In practice, even if the variable is initialized upon declaration, it doesn’t satisfy any callers  In the example below, if we define variable toBeHoisted , but initialize it after function caller, then we will have an error

function caller(){
  let x = toBeHoisted;
  console.log(x+5);
}

caller()  //toBeHoisted is not defined, we get NaN

var toBeHoisted = 95;

 

To see that hoisting does affect variables, we could initialize the variable BEFORE declaring it, and then the declaration is hoisted.

toBeHoisted = 95;

function caller(){
  let x = toBeHoisted;
  console.log(x+5);
}

caller() //100

var toBeHoisted;

.

As an aside, if we change from a var decleration to let decleration, that will not be hoisted and we get an error

toBeHoisted = 95;

function caller(){
  let x = toBeHoisted;
  console.log(x+5);
}

caller() //ReferenceError: toBeHoisted is not defined

let toBeHoisted;

.

The rest parameter (…args) vs the arguments object

Posted on Updated on

The rest parameter (…args) vs the arguments object

So I was listening to the Syntax.fm podcast, which is about various web development topics. In one of the episodes they were talking about the rest parameter, and one of the hosts had mentioned that they were using it often. I decided to check it out. According to Mozilla “the rest parameter syntax allows us to represent an indefinite number of arguments as an array.”[A] Just by looking at this statement, I realize how useful this could be. One scenario that crossed my mind was if we have an unknown number of arguments bein passed in, we can rely on the rest parameter to handle the acceptance, then use the functions logic to form a logic path based on the number of arguments being passed in.

Why not use the arguments array?

A good question would be, why care about the rest parameter, if JavaScript already has an arguments array? Well, the thing is, the arguments OBJECT is an ARRAY-LIKE STRUCTURE, meaning it’s not an array. It’s like an array, in that we can access arguments inside the “arguments object” by using indexed entries, such as argument[3]. Unlike an array, we cannot use array features such as map, push, pop, etc. As per Mozilla, it “does not have any Array properties except length.”[B] What the rest parameter does is place unnamed arguments inside an array, which we can manipulate as any other array.

Why use the arguments object at all?

The arguments object does still have it’s uses. Only unnamed parameters are placed in the rest parameter, so to access named parameters you still need to use their binding names, or reference their index in the arguments object. Another feature that the arguments object has is the callee function, which holds the current executing function. This itself can be it’s own topic, so I’ll let the reader look it up further for now.

In conclusion, both labels have their own reasons to be used, and I would like to think of them as complementary to each other.

ECMAScript 2017 padEnd() and padStart()

Posted on

Two new methods implemented in the 2017 version of Javascript are padEnd and padStart. Both methods pad a string with second string, until the result is of the desired indicated length. Given that the return value of padEnd and padStart are new Strings, and the original strings are unmodified, the methods a “pure”, as they do not cause side-effects.  As you can see from the examples below, this is true as str1 in the example is unmodified.

Screen Shot 2018-09-08 at 1.04.49 AM

Now the length of our example string, str1 is 17.  If the target length is less than the size of the primary string, the primary string will be returned. If the target length is less than the size of the primary string and the added string, the added string will be truncated to fit the target length. Example below:

Screen Shot 2018-09-08 at 1.14.54 AM.png

If your browser doesn’t have these methods because it doesn’t support ECMAScript 2017 you can actually write your own methods and add them to the String prototype, extending it. I changed the styling such that it can fit in a smaller picture, so heres an example of padEnd() implemented by me: below. See also the repl link if you would like to play with it

Screen Shot 2018-09-08 at 1.37.56 AM

Screen Shot 2018-09-08 at 1.42.44 AM.png

Uncaught TypeError: Super expression must either be null or a function, not undefined in React app

Posted on Updated on

Running a react app, nothing is showing up.

This is the error I am getting in console:

Uncaught TypeError: Super expression must either be null or a function, not undefined

From bundle.js:22486

In console, I  expand and click on the link to  bundle.js:22486

I get back this line, but the important part is at the end:

    function _inherits(subClass, superClass) { if (typeof superClass !== “function” && superClass !== null) { throw new TypeError(“Super expression must either be null or a function, not ” + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // import React, {Componenet} from ‘react’

Can you see what was wrong?

I spelled Component wrong. But the error doesn’t directly say that, you need to dig a little.

One I fixed the error, I was able to see my app

React: TypeError: Cannot read property ‘request’ of undefined

Posted on

I was getting the error : TypeError: Cannot read property ‘request’ of undefined  while I was building a react lab.

 

I noticed it said something about components not installed. I had ran npm install before but that wasn’t the fix.

 

yarn install is what fixed it, looks like some packages depended on yarn rather than npm.