Node.js

245

Solutions

361

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Share tech news, updates, or what's on your mind.

Sign up to Post

I am new to sequelize and I created a middleware called "db.js" with a connection to a mysql table called "users". Everytime, I attempt to run the app.js, I am getting this error: "TypeError: app.use() requires a middleware function".

However, I have a middleware function. See the code below: Am I missing something? I have the module.exports object at the end.

Should I have initialize sequelize?

Here is the db.js file:
const Sequelize = require("sequelize");
const mysql = require("mysql");
const mysql2 = require("mysql2");

const db = {}
const sequelize = new Sequelize("smalldata", "root", "xxxx", {
    host: "localhost",
    dialect: "mysql",
    operatorsAliases: false,

    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 90000
    }
})

sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db;

Open in new window


Here is the app.js file:


const sequelize = require("sequelize");
const db = require("./middleware/db");
const express = require("express");

//Initialize Middleware
app.use(cors());
app.use(expressLayouts);
app.use(logger);
app.use(db);

Open in new window



Here is the users.js file for the mysql table:

const Sequelize = require("sequelize");
const db = require("./db");

const User = db.sequelize.define(
    'users',
    {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },

        first_name: {
            type: Sequelize.STRING
        },

        last_name: {
            type: Sequelize.STRING
        },

        email: {
            type: Sequelize.STRING
        },

        password: {
            type: Sequelize.STRING
        }
    },

    {
        timestamps: true
    },
)

// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
    // Now the `users` table in the database corresponds to the model 
    definition
    return User.create({
        first_name: 'John',
        last_name: 'Hancock',
        email:'johnhancock@gmail.com',
        password:'johnny'
    });
});

module.exports = User

Open in new window

0
I have a profile photo which the user can update. What SHOULD happen is that when they upload a new photo, the database is updated and the old photo is deleted. However, what is happening is that the database is updated correctly, but the newly uploaded image is deleted meaning there is no image at all now. I also tried deleting the file synchronously using fs.unlinkSync but had the same result.

const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/img");
  },
  filename: (req, file, cb) => {
    const ext = file.mimetype.split("/")[1];
    cb(null, `hero-${Date.now()}.${ext}`);
  }
});

// test if uploaded file is an image
const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image")) {
    cb(null, true);
  } else {
    // throw error here
    cb(console.log("not an image"), false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter
});
exports.uploadUserPhoto = upload.single("bgImg");

Open in new window



exports.updateHeroImg = async (req, res) => {
  const updateId = "5d13b3c6dd57c43828ed5a7a";
  if (req.file) bgImgNew = req.file.filename;
  //find current image name in database
  const hero = await Hero.findById(updateId);
  if (!hero) return;

  // helper function to delete files
  fileHelper.deleteFile("public/img/" + hero.bgImg);

  // set new db record image name
  hero.bgImg = bgImgNew;

  // update database
  const result = await hero.save();
  res.status(200).send("image uploaded");
};

Open in new window

Helper delete function

const fs = require("fs");

const deleteFile = filepath => {
  fs.unlink(filepath, err => {
    if (err) {
      throw err;
    }
  });
};

exports.deleteFile = deleteFile;

Open in new window


My route:

router.post("/", heroController.uploadUserPhoto, heroController.updateHeroImg);

Open in new window

0
Hi,

I would like to use nodejs for enabling an ad user to upload a local file to a server. It should be uploaden in a folder with the ad users name.
Have no experience with nodejs.
Please advise howto.

Note: have working code in powershell, now need a web interface for it.

J
0
Hi guys,
I am trying to check login in a external website and I am using node.js.
the site I am trying to check the login contain form that submit username and password:
Here is the dom of this website:
<form action="/PSAWeb/login" id="LoginForm" method="post" novalidate="novalidate">        <div class="sixteen columns">
            
            <div id="FakeSummary" class="validation-summary-errors">
                <ul id="validation-ul"></ul>
            </div>
        </div>
        <fieldset class="five columns">
            <legend>Log In</legend>
            <ol>
                <li>
                    <label for="Username">Username</label>
                    <input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" value="">
                </li>
                <li>
                    <label for="Password">Password</label>
                    <input id="Password" name="Password" required="Required" type="password" class="form-control" autocomplete="off" aria-required="true">
                    <span toggle="#Password" style="float:right; margin-right:5px; margin-top:-30px; position:relative; z-index:2; display:none;" class="togglePassword"><i class="icon-eye-open icon"></i></span>
                </li>
                    <li>
                        <label for="Schema">Database</label>
                        <div id="SchemaChosen">
                            <span 

Open in new window

0
I am trying to display unique records grouped by the particular slug passed in.

My output in postman looks like this though:

	"subcats": [
	  {
		"_id": {
		  "subcategory": {
			"_id": "5d2b42c47b454712f4db7c37",
			"name": "shirts"
		  }
		}
	  }
	]

Open in new window


My desired output would be more like:

"subcats": [
  {
        "_id": "5d2b42c47b454712f4db7c37",
        "name": "shirts"
  }
]

Open in new window

An example of a product in the database:

 
       "_id": "5d39eff7a48e6e30ace831dc",
        "name": "A colourful shirt",
        "description": "A nice colourful t-shirt",
        "category": {
            "_id": "5d35faa67b19e32ab3dc91ec",
            "name": "clothing",
            "catSlug": "clothing"
        },
        "subcategory": {
            "_id": "5d2b42c47b454712f4db7c37",
            "name": "shirts",
            "catSlug": "shirts"
        },
        "price": 19
    }

Open in new window


I don't want that top level `_id` there with everything nested inside of it.

I tried using `$project` but then I just end up with an empty array.

      const products = await Product.find({ "category.catSlug": catslug }).select({
        name: 1,
        description: 1,
        price: 1,
        category: 1
      });

    const subcats = await Product.aggregate([
      { $match: { "category.catSlug": catslug } },
      { $group: { _id: { subcategory: "$subcategory" } } }
      { $project: { _id: 0, name: 1 } }
    ]);

    Promise.all([products, subcats]);
      res.status(200).json({
        products,
        subcats
      });

Open in new window

0
I am trying to understand node/javascript async / promise features.  While doing this I ran across an example that confuses me.  Here is the example, and the questions are below:
From https://codeburst.io/javascript-promises-explained-with-simple-real-life-analogies-dd6908092138

const loadImage = url => {
  return new Promise(function(resolve, reject) {

    //Open a new XHR
    var request = new XMLHttpRequest();
    request.open('GET', url);

    // When the request loads, check whether it was successful
    request.onload = function() {
      if (request.status === 200) {
        // If successful, resolve the promise
        resolve(request.response);
      } else {
        // Otherwise, reject the promise
        reject(Error('An error occurred while loading image. error code:' + request.statusText));
      }
    };

    request.send();
  });

};

Open in new window


1. Why create a promise for this?  Isn't XMLHttpRequest already async?  It makes a request, and then you feed onload a function to call when it is done.
2. onload documentation says, "to be executed when the request completes successfully".  So in the example above onload is used for a resolve or a reject.  If onload only fires on success how would the failure portion of the IF (line 13) every be reached?
0
I have the following code to insert, edit and delete records from a database using node.js.  I would like to have alert messages informing the user of the successful transaction for each from the frontend if successful.  I am not certain regarding the syntax for this.

Here is the code to insert into the database:
$(document).ready(() => {
    $(document).on('click', '.insert', function (e) {
     // $('#insertD').click(() => {
      e.preventDefault();
      $("#insertE").remove();
      $("#insertD").show();
      $("#stationForm")[0].reset();
      $("#stationForm").attr({
        action: $(e.target).attr("href"),
        //action: "/station", // PATH TO POST NEW STATION DATA ?
        method: "POST"
      });
   
      $("#modalStationForm")
        .dialog("option", "title", "Inserting New Station")
        .dialog("open");
      });
[/code}


Here is the code edit code:
[code]
$(document).ready(() => {
    $(document).on('click', '.edit', function (e) {
      e.preventDefault();
      $("#insertD").hide();
      $("#insertE").show();
      $("#stationForm")[0].reset();
      $("#stationForm").attr({
        action: $(e.target).attr("href"),
        //action: "/station", // PATH TO POST NEW STATION DATA ?
        method: "PUT"
      });
      var value = $(event.target).closest("div").find("input:hidden").val();
      value = JSON.parse(value);

      $("#store", "#modalStationForm").val(value.Station);
      $("#location", 

Open in new window

0
After attempting to edit a mysql record in node.js, I am receiving null results when I review the mysql query report and the affected rows are returning zero.  There is no change to the record. However, the backend says that the results are not null, the sql query is not null and that the req.body for all the values are not null.

Here is the mysql general query log:

190717 16:42:40	    3 Query	SELECT * FROM stores
		    3 Query	SELECT * FROM stores
		    3 Query	SELECT * FROM stores
190717 16:42:42	    3 Query	SELECT * FROM stores
190717 16:43:13	    3 Query	UPDATE stores SET `station` = NULL, `address` = NULL, `monthly c-store sales` = NULL,`operator` = NULL, `top sku` = NULL WHERE `id` = NULL

Open in new window


These are the results returned on the frontend:

affectedRows: 0
changedRows: 0
fieldCount: 0
insertId: 0
message: ""
protocol41: true
serverStatus: 2
warningCount: 0

Open in new window


However, the backend says that the values are not null after putting in the following code:

if (results !== null) {
        console.log('results is not null');
        }else{
        console.log('results is null');
        };


      if (sql !== null) {
      console.log('sql is not null');
      }else{
      console.log('sql is null');
      };

      if (req.body.Station !== null) {
        console.log('req.body is not null');
        }else{
        console.log('req.body is null');
        };

Open in new window


Here are the results.....
{ station: 'Hopefully',
  address: 'this',
  monthlycstoresales: '200',
  operator: 'will',
  topsku: 'work',
  id: '7' }

results is not null

sql is not null

req.body is not null

Open in new window



Here is the backend code:

Open in new window

0
I'm supporting a spark scala application with node js front end with d3 js etc.,. The spark uses spark job server for taking in api requests in the form of curl json inputs and return back json outputs. I'm getting a too many open files issues.

09:27:23.649 [task-result-getter-1] WARN  o.a.spark.scheduler.TaskSetManager - Lost task 0.0 in stage 151.1 (TID 10373, localhost, executor driver): java.io.FileNotFoundException: /data/iot/installs/data/spark_work/blockmgr-952fad2f-2721-41da-a513-aebc7fc83c1a/35/shuffle_65_0_0.index.ffe8ecd3-64ab-445f-8fa7-8ba9aefcdeff (Too many open files)
      at java.io.FileOutputStream.open0(Native Method)
      at java.io.FileOutputStream.open(FileOutputStream.java:270)
      at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
      at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
      at org.apache.spark.shuffle.IndexShuffleBlockResolver.writeIndexFileAndCommit(IndexShuffleBlockResolver.scala:144)
      at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:127)
      at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:96)
      at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
      at org.apache.spark.scheduler.Task.run(Task.scala:109)
      at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at …
0
Data Tables are not being displayed with data from the database.  I am receiving the following error:

jquery.dataTables.min.js:40 Uncaught TypeError: Cannot read property 'length' of undefined

Here is the code:

<!--Data Tables:css-->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<!--Data Tables-->
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

$(document).ready(function () {
$('#datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://localhost:5000/alldata",
"type": "GET"
},
"columns": [
{ "data": "ID" },
{ "data": "Station" },
{ "data": "Address" },
{ "data": "C-Store Sales" },
{ "data": "Operator" },
{ "data": "Top SKU" }
]
});
});

Open in new window


<!---(2b)-->
    <h3>Data Table</h3>
    <form id="form1">
      <table class="table table-bordered table-striped" id="datatable">
        <thead>
          <tr>
            <th>ID</th>
            <th>Station</th>
            <th>Address</th>
            <th>C-Store Sales</th>
            <th>Operator</th>
            <th>Top SKU</th>
          </tr>
        </thead>
      </table>
    </form>

    <hr>

    <br />

Open in new window

0
I'm going through a Node tutorial and I'm at the point where I'm working with "express-validator."

According to the docs, "express-validator" is "...a set of express.js middlewares that wraps validator.js validator and sanitizer functions."

Easy enough, but I want to better understand that definition and it's bugging me that I've never installed the "validator.js" library.

Here's what I understand:

Middleware acts as a bridge between two applications. In the context of Node, Express is middleware specifically in the way it intercepts and interacts with the request and the response objects that are coming from the DOM (feel free to stop me at any time if I'm not accurate).

A "wrapper," according to https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_wrap_element, is something that's going to "wrap" around a div...

So, going back to the original definition, it looks as though Express-Validator is wrapping around the "validator.js" library and making it more intuitive to use.

But where does "validator.js" come from? I've never installed it, so how did that become use-able?

And then when I look at the example of the Jquery "wrap" method (https://www.w3schools.com/jquery/html_wrap.asp)...

How does express-validator "wrap" around validator.js?
0
Hello expert,

Have an Excel spreadsheet on complex project called 'SFTP'.
Excel spreadsheet has a ton of detail on project
but there is so much info that it is hard to see where one
customer is in the SFTP set up process.

So created a Visio that details the process and then
inserted the customers showing where the
customers were in the process, attached.

It would be great if clicking on the Visio customer
node would take the user to the line in Excel
for that customer.

Have tried a couple of online tutorials about how to
link Visio to Excel.
https://classroom.synonym.com/visio-objects-excel-13927.html

But this and others like it explain how to link a Visio
shape to Excel data. All that is required for this project
is to link a Visio shape or text to a row or cell in Excel.

Is this possible?

A link has been created in the past using JavaScript
to create a hot spot on a GIF in an HTML file
that links to another HTML file.

But I was hoping that Microsoft had integrated
there apps enough to go between Visio and Excel

Thanks.

Allen
Payer_TPA_SFTP_process_190701.gif
0
As an example, I want to have food categories, sub categories and the actual menu items themselves. All menu items have to have a category, but not all have to have a sub-category.

So, something like:

Example of category only:

Hamburgers
     - Bacon and cheese
     - Chicken 

Open in new window


Example of category and sub-category:

Pizza
    Traditional
       - Cheese and mushroom
       - Tomato and ham
   Deluxe
      - Bacon, ham, salami, steak

Open in new window


This means the sub category is optional. So, when building the form to add a menu item, should there be an option for none on the subcategory or if nothing is selected from the dropdown menu would it be fine to insert an empty string into the database?

This is what my schema looks like but not sure if it is right for what I need. I am

const menuSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlenth: 255
  },
  description: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  category: {
    type: categorySchema,
    required: true
  },
  subcategory: {
    type: subcategorySchema
  }
});

const Menu = mongoose.model("Menu", menuSchema);

Open in new window

   
The category and subcategory schema are pretty much the same but would it be better to have 2 separate schemas for category and subcategory or have just a categories schema with an embedded subcategory within it?

const categorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 5,
    maxlength: 255
  }
});

const Category = mongoose.model("Category", categorySchema);

Open in new window

0
I realize I might be getting into some detail that isn't especially necessary, but I'm interested nevertheless.

In Node, you have the ability to secure your online transactions through a CSRF token. Anytime I'm using a form, I can assert a CSRF token to ensure that the system isn't being breached by some sinister party.

I'm going through a portion of a tutorial right now where I'm sending an email to someone who needs to reset their password. A part of the URL that they click on to do that includes a random value that's being generated using a NodeJs library called "crypto."

My question is: What's the difference?

They both appear to be random values and they both appear to be doing the same thing as far as adding a layer of security. But what makes them different?

Thanks!
0
I'm using MongoDBStore to store my session values which include my user object.

The tutorial I'm going through has the session document looking like this:

screenshot of session doc
Notice how the user object contains the "_id" field.

My current project, as far as the session collection is concerned, looks like this:

screenshot of no _id
I can't figure out why the "_id" field isn't being added to the "sessions" table.

I'm new to Node, so I'm not altogether certain what files you would need to see in order to effectively troubleshoot this puppy, but let me start with my app.js file and several others.

Thanks in advance for your help!

app.js :

const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");
const flash = require("connect-flash");

const errorController = require("./controllers/error");
const User = require("./models/user");

const MONGODB_URI =
    "mongodb+srv://username:password@somewhere.mongodb.net/landing_pages";

const app = express();

const store = new MongoDBStore({
    uri: MONGODB_URI,
    collection: "sessions"
});
const csrfProtection = csrf();

app.set("view engine", "ejs");
app.set("views", "views");

const startRoutes = require("./routes/start");
const authRoutes = require("./routes/auth");

Open in new window

0
What is the best way to access an MS Access Table within an MS SQL Server? I know how I could use an MS SQL Table within MS Access, but I need it the other way around.

What we like to do; there is an MS SQL Server we access existing tables by node.js. We would need some data from MS Access joined by MS SQL Tables in views.
0
I need a simple example of reading and parsing a text file in Node.JS.
We have some code to hack but no experience in the language.
It would be a very small file - with only around 7 parameters to read. These the would be displayed through the GUI.
I'm not sure if it'll need to be need need to be asynchronous yet.
1
Hi there,

Is there a way we could convert a VMware VM CD-ROM in vCenter from SATA to IDE without downtime? If there is, how should we do this as it restricted us to update from the GUI. Thinking if we could do this from the command line  converting the affected virtual machine CD-ROM virtual device node from SATA to IDE on the fly without shutdown BUT no idea how to do this.

Any help is GREATLY appreciated.

Thanks and regards,

Jun
0
This may be more a matter of taste rather than a technical question:

I have a web app that I'm going to be selling Membership access to. I'd like to use Shopify as the Merchant Account/Gateway in which I will need to purchase and configure two plugins:

1. A Recurring Subscription plug-in that will allow me to charge Customer's 30 days out from when they subscribed and keep that payment recurring for a given duration
and
2. An "Affiliate" plug-in as I will be paying a Sales Team a portion of the initial cost from the Customers.

I realize this is a big ask and I'm fairly new to Shopify, so please use laymen's terms with your suggestions. The app is written in Node.JS/React so I suspect that integration won't be too difficult for the Devs.

Thanks for your assistance.
0
Hi
Node.js
Calling the library https://github.com/naptha/tesseract.js#tesseractjs

We call the function worker.recognize(path2png, language) for OCR of a PNG in a await function.

async function readPNG(path2png, language) {
 const worker = new TesseractWorker();
 try{
   let result = await worker.recognize(path2png, language);
    return result.text;
 } catch (error) {
   console.error("************************** error=",error)
 } 
}

Open in new window


There is a crash in tesseract and we would expect that it lands in the catch(error), but it does not. Instead, we get this and no callback.

contains_unichar_id(unichar_id):Error:Assert failed:in file /src/src/ccutil/unicharset.h, line 502
trap!
trap!
abort("trap!"). Build with -s ASSERTIONS=1 for more info.
abort("trap!"). Build with -s ASSERTIONS=1 for more info.

/home/diego/NetBeansProjects/FromGitHub/tmp/localsearch_triage/node_modules/tesseract.js-core/tesseract-core.js:8
var Module=typeof TesseractCoreWASM!=="undefined"?TesseractCoreWASM:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}Module["arguments"]=[];Module["thisProgram"]="./this.program";Module["quit"]=(function(status,toThrow){throw toThrow});Module["preRun"]=[];Module["postRun"]=[];var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof 

Open in new window

0
I'm looking for a macro to help to me count and display direct and indirect subordinates in Visio Org Charts. I found the sample one online below, but I running into issues with the
"s.Shapes(4).Text = dc" portion.

Function RecursiveCount(s As Shape) As String
    Dim count As Integer
    
    count = 0
    dc = s.FromConnects.count - 1
    
    For i = 1 To s.FromConnects.count
       If s.Text <> s.FromConnects(i).FromSheet.Connects(2).ToSheet.Text Then
            count = count + 1
            rc = RecursiveCount(s.FromConnects(i).FromSheet.Connects(2).ToSheet)
            count = count + rc
       End If
    Next
    If dc > 0 Then
        s.Shapes(4).Text = dc
        If (count > 0) And (count <> dc) Then
            s.Shapes(4).Text = s.Shapes(4).Text & "(" & count & ")"
        End If
    End If
    RecursiveCount = count
End Function
 
Sub CountSubs()
    ' select the top most node then run this macro
    Dim s As Shape
    Set s = ActiveWindow.Selection(1)
    
    ' now recursively update counts
    i = RecursiveCount(s)
    
End Sub
 
Sub SetCountsToBlank()
Dim s As Shape
For Each s In ActivePage.Shapes
        If s.Shapes.count >= 4 Then
            s.Shapes(3).Text = ""
            s.Shapes(4).Text = ""
    
        End If
    Next
End Sub

Open in new window

0
Am I explaining this function correctly? Am I using the right terms and logic?

Here's my method:

addOrder() {
❶ const db = getDb();
② return this.getCart()
  .then(products => {
	const order = {
	  items: products,
	  user: {
		_id: new ObjectId(this._id),
		name: this.name,
		email: this.email
	  }
	};
	❸ return db.collection("orders").insertOne(order);
  })
  ❹ .then(result => {
	this.cart = { items: [] };
	return db
	  .collection("users")
	  .updateOne(
		{ _id: new ObjectId(this._id) },
		{ $set: { cart: { items: [] } } }
	  );
  });
}

Open in new window


I want to be able to understand this, not just in terms of its logical flow, but also in the theory behind it so I can explain it to others...

Here's what I've got. Let me know if I've nailed it or I need to tweak my understanding.


① I'm establishing my database connection

② you'll need to return the result of the "then" block so your controller has a result to publish. That part of the Controller looks like this:

exports.getOrders = (req, res, next) => {
  req.user
    .getOrders()
    .then(orders => {
      res.render("shop/orders", {
        path: "/orders",
        pageTitle: "Your Orders",
        orders: orders
      });
    })
    .catch(err => console.log(err));
};

In addition, the result of the "getCart" is going to be all of the data that's coming from the "getCart" method which includes the productId and the quantity. You'll throw that in the "items" object and then …
0
When I try to start coding a new Angular app using  "ng new myFirstApp", I am getting the error:

-bash: /Users/jlpereira/.npm-global/bin/ng: No such file or directory

can anyone help?
0
Hi Experts,

I am working on reactJs(redux and redux thunk) application on front-end and django and nodejs on the back end.  I have a question.  I would like to know, how to reset the state (redux) to the initial state in the middle of the application.  Can anyone provide me with an idea of how to do this?

Thanks
0
Hi Experts,

I am working on an application with Reactjs as front end (Redux , redux thunk, reactjs) and django and nodejs on backend,  I get the following runtime error

 Unhandled Rejection at: Promise {
[1]   <rejected> TypeError: Cannot read property 'facets' of undefined
[1]     at searchComplete (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/search/static/search/reducers/search.js:140:59)
[1]     at search (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/search/static/search/reducers/search.js:246:14)
[1]     at combination (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux/lib/combineReducers.js:133:29)
[1]     at dispatch (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux/lib/createStore.js:178:22)
[1]     at /home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux-thunk/lib/index.js:14:16
[1]     at /home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/react-router-redux/middleware.js:18:18
[1]     at dispatch (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux/lib/applyMiddleware.js:45:18)
[1]     at _callee$ (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/search/static/search/actions/search.js:171:15)
[1]     at tryCatch (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/babel-cli/node_modules/regenerator-runtime/runtime.js:65:40)
[1]     at Generator.invoke [as _invoke] 

Open in new window

0

Node.js

245

Solutions

361

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Top Experts In
Node.js
<
Monthly
>