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

The following code works just fine:

app.use((req, res, next) => {
  if (!req.session.user) {
    return next();
  }
  User.findById(req.session.user._id)
    .then(user => {
      if (!user) {
        return next();
      }
      req.user = user;
      next();
    })
    .catch(err => {
      throw new Error(err);
    });
});

Open in new window


 I'm just wondering what the difference is between next(); and return next();

The way that I've seen it explained on the web is that when you write "return next();" you're "...compelling your app to stop the execution of the code once the callback is completed."

The first thing that's happening is I'm looking for the presence of a session id. If one is not present, I'm thinking that "next" in this case is referring to the User.findById dynamic, yes? And because it's coded alongside "return," that definitively routes the code to the next piece.

Yes?

You wouldn't HAVE to write "return," but it's a good practice, especially in this instance correct?

But here's where I start getting a little fuzzy.

You're now in the "User.findById" piece and if you dop't find a user you get "return next();." Well, what is "next?"

I might be misinterpreting "next" to mean the next piece of the surrounding code.

Bottom line: I'm a little confused as to what "next" means and the difference between using "return next" and simply "next."

Can you help a brother out?
0
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

hi

how can i remove a node from html collection xml in javascript
0
Hello Experts

I am looking for a little direction on a project.  It may be preference, but how do you all start and go about writing your code?


The project will use node, express and mySql with a a react/handlebar front.  The user will add, update, view and report on records of entry.  


Do you start with your front side user entry skeleton? Or do you start with the back side getting the database connected and the server created and work forward?


Thanks,
Ed
0
Here's my code:

require("dotenv").config();

const express = require("express");
const mongoose = require("mongoose");
const csrf = require("csurf");
const bodyParser = require("body-parser");

const app = express();
const conn = process.env.CONNECTION;
const csrfProtection = csrf();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);

const loginRoutes = require("./routes/login");
const authRoutes = require("./routes/auth");
const createRoutes = require("./routes/create");

app.use((req, res, next) => {
  res.locals.csrfToken = req.csrfToken();
  next();
});

app.use(loginRoutes);
app.use(authRoutes);
app.use(createRoutes);

mongoose
  .connect(conn)
  .then(result => {
    app.listen(5000);
  })
  .catch(err => {
    console.log(err);
  });

Open in new window


I'm getting an error that says my csrf token is misconfigured and I don't know what to do or where to start.

Here's the whole error:

Error: misconfigured csrf
    at csrf (C:\wamp\www\authentication\node_modules\csurf\index.js:71:19)
    at Layer.handle [as handle_request] (C:\wamp\www\authentication\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\wamp\www\authentication\node_modules\express\lib\router\index.js:317:13)
    at C:\wamp\www\authentication\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\wamp\www\authentication\node_modules\express\lib\router\index.js:335:12)
    at next 

Open in new window

0
I'm using Postman to build an API in Node. Here's a portion of my Controller:

 const first_name = req.body.first_name;

Easy, enough...

The thing is, I'm getting a message in Postman that says: "TypeError: Cannot read property &#39;first_name&#39; of undefined<br> &nbsp; &nbsp;at exports.postCreate (C:\wamp\www\authentication\controllers\create.js:9:23)"

Here's the way I've got my Postman dynamic set up:

postman screenshot
Why is Postman not seeing what I'm assuming are my form fields?
0
I have put the zip file from https://www.c-sharpcorner.com/article/pnp-people-picker-control-for-spfx/ into a webpart (after unzipping it). I'm trying to update my Sharepoint list.

With the PersonName field (Set as Person or Group in Sharepoint online) commented out it works. However when the PersonName field is not commented out it fails with this message. I followed the import instructions, but was wondering if my node modules directory is incorrect or if there is a difference between the Sharepoint used and my version of sharepoint online.

```
  @autobind 
 private addSelectedUsers(): void {  
 sp.web.lists.getByTitle("AlistairTest").items.add({
  Title: getGUID(),
  //With these lines commented out it works.  I changed the field name from User to PersonName when 
  //I created the column.
  PersonName: { 
      results: this.state.addUsers
  }
   }).then(i => {
    console.log(i);
   });
} 
```

Open in new window

Failed to load resource: the server responded with a status of 400 () [https://bhfonline.sharepoint.com/teams-and-projects/dev/halperna/_api/web/lists/getByTitle('AlistairTest')/items] Error: Error making HttpClient request in queryable [400] ::> {"odata.error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"A node of type 'PrimitiveValue' was read from the JSON reader when trying to read the entries of a feed. A 'StartObject' or 'EndArray' node was expected."}}} at new HttpRequestError (d:\spfx-pnp-people-picker\dist\pn-p-people-picker-web-part.js:2364:29) at d:\spfx-pnp-people-picker\dist\pn-p-people-picker-web-part.js:2373:21
0
I've got Docker installed and I've downloaded a boilerplate from https://github.com/kunalkapadia/express-mongoose-es6-rest-api

Everything's installed including "yarn" - all good.

But when I run this: $ bash bin/development.sh, which, from what I understand is instantiating the docker dynamic, it just hangs on "3.4: Pulling from library/mongo."

Here's what it looks like:

screenshot
I am poised on the threshold of greatness! I've got my Node syntax proofed and ready! All I've got to do is drop it into the Boilerplate and wrap it in a Docker image and I will be done!

But I can't get past this thing and I'm stuck!

Thoughts?
0
I've got a working app that I'm trying to assimilate into a Boilerplate. I'm thinking we're poised on the threshold of great things, but I'm stuck at the section where I've got to instantiate my Mongodb connection.

Here's the "index.js" code:

const mongoose = require('mongoose');
const util = require('util');

// config should be imported before importing any other file
const config = require('./config/config');
const app = require('./config/express');

const debug = require('debug')('express-mongoose-es6-rest-api:index');

// make bluebird default Promise
Promise = require('bluebird'); // eslint-disable-line no-global-assign

// plugin bluebird promise in mongoose
mongoose.Promise = Promise;

[b]// connect to mongo db
const mongoUri = config.mongo.host;
mongoose.connect(mongoUri, { server: { socketOptions: { keepAlive: 1 } } });
mongoose.connection.on('error', () => {
  throw new Error(`unable to connect to database: ${mongoUri}`);
});[/b]

// print mongoose logs in dev env
if (config.mongooseDebug) {
  mongoose.set('debug', (collectionName, method, query, doc) => {
    debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc);
  });
}

// module.parent check is required to support mocha watch
// src: https://github.com/mochajs/mocha/issues/1912
if (!module.parent) {
  // listen on port config.port
  app.listen(config.port, () => {
    console.info(`server started on port ${config.port} (${config.env})`); // eslint-disable-line no-console
  });
}

Open in new window

0
Here's my code:

mongoose
  .connect(conn)
  .then(result => {
    const newPassword = bcrypt.hash("sectac", 12);
    console.log(newPassword);
    app.listen(5000);
  })
  .catch(err => {
    console.log(err);
  });

Open in new window


This is the tail end of my code and what I'm getting ready to do is insert a new user and I want to include an encrypted password. In this case, "setac."

I'm getting this error:

Promise { <pending> }

I'm thinking this is a classic case where Node is plowing ahead without waiting for the calculation / functionality to finish before it moves on.

How do I need to position this so I can get the encrypted password and log it.

What am I missing?
0
I've got a legitimate bearerToken and a solid security.token and they both match upon visual inspection. But I keep getting a "forbidden" response and I don't know why.

What am I missing?

function verifyToken(req, res, next) {
  const bearerHeader = req.headers["authorization"];

  if (typeof bearerHeader !== "undefined") {
    const bearer = bearerHeader.split(" ");
    const bearerToken = bearer[1];
    Authorization.findById(tokenID).then(security => {
      console.log(security.token);
      if (bearerToken == security.token) {
        next();
      } else {
        res.sendStatus(403);
      }
    });
  }
}

Open in new window

0
Rowby Goren Makes an Impact on Screen and Online
LVL 13
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Here's a portion of my app.js file:

const express = require("express");
const jwt = require("jsonwebtoken"); //this is the package that decrypts your token
const mongoose = require("mongoose");
//const compression = require("compression");

const app = express();
const superPassword = process.env.SIGNATURE; //here's where you're grabbing your SIGNATURE constant from your .env file that's in your root directory
const conn = process.env.CONNECTION;

const Auth = require("./models/auth");

Open in new window


Here's my "auth.js" model:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const authSchema = new Schema({
  app: {
    type: String,
    required: true
  },
  token: {
    type: String,
    required: true
  }
});

module.exports = mongoose.model("Auth", authSchema);

Open in new window


I'm expecting to see a new "auth" collection in my MongoDB but I'm not seeing it.

Am I missing something?
0
I am getting an error when I run my node app using sequelize - 'Unknown column \'general_comments\' in \'field list\''. However, as seen below, I have a model with the column....general_comments.  Please see the error log below and the model code for compressor

Server started on port 5000
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
http://localhost:5000/api/alldatac:2019-09-19T05:03:25-04:00
Executing (default): SELECT `compressor_house_id`, `equipment_area`, `equipment_type`, `photo_image`, `manufacturer`, `model_number`, `serial_number`, `service`, `capacity`, `severity`, `general_comments`, `createdAt`, `updatedAt` FROM `compressor_houses` AS `compressor_house`;
{ SequelizeDatabaseError: Unknown column 'general_comments' in 'field list'
    at Query.formatError (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\sequelize\lib\dialects\mysql\query.js:244:16)
    at Query.handler [as onResult] (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\sequelize\lib\dialects\mysql\query.js:51:23)
    at Query.execute (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\mysql2\lib\commands\command.js:30:14)
    at Connection.handlePacket (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\mysql2\lib\connection.js:408:32)
    at PacketParser.Connection.packetParser.p [as onPacket] (C:\Users\Chrystelle\Omar 

Open in new window

0
Record
I am using the "each statement" with the handlebars template engine in node.js.  Unfortunately, each record is being tabbed to the right of the previous one, as the attach image shows. I would like each record to line up evenly.
Please see the code:

Here is the file:gigs.handlebars

{{#each gigs}}
<section id="gigs" class="container">
<!--<h1>All Gigs</h1>-->
<h1>{{equipment_area}}</h1>
<div class="gig">
      <h3>{{title}}</h3>
      <!--<p>{{manufacturer}}</p>-->
      <ul>
        <!--<li>Budget: {{budget}}</li>-->
        <!--<li><a href="mailto:{{contact_email}}" class="btn btn-reverse">Apply Now</a></li>-->
        <li>Equipment Type: {{equipment_type}}</li>
        <li>Manufacturer: {{manufacturer}}</li>
        <li>Model Number: {{model_number}}</li>
        <li>Serial Number: {{serial_number}}</li>
        <li>Condition: {{severity}}</li>
        <li>Comments: {{general_comments}}</li>
                
      </ul>
      <!--
      <div class="tech">
        <small>Technologies Needed: <span>{{technologies}}</span></small>
      </div>
      -->
    </div>
    {{else}}
     <p>No gigs available</p>
    {{/each}}
</section>

Open in new window


Please also see the css file:
@import url('https://fonts.googleapis.com/css?family=Lato');

:root {
  --primary-color: #568c9b;
  --primary-hover-color: #64a5b7;
  --bg-color: #333;
  --box-shadow: 3px 4px 12px rgba(0, 0, 0, 0.7);
}

* {
  box-sizing: border-box;
}

body {
  font-family: 'Lato',

Open in new window

0
I have an xml declared as:
declare @xmlIndata xml = '<root>
  <FromDate>2018-04</FromDate>
  <ToDate>2019-08</ToDate>
  <Period />
  <Units>
    <Unit>
      <Name>1</Name>
    </Unit>
  </Units>
  <Variables>
    <Variable>
      <Name>N05C</Name>
    </Variable>
    <Variable>
      <Name>N06A</Name>
    </Variable>
    <Variable>
      <Name>PeopleCount</Name>
    </Variable>
  </Variables>
  <Filters />
</root>'

Open in new window


I want to extract the subtree starting at the node <Variables>.  So some xml manipulation to extract the subtree and set it to @variables. Like:

declare @variables xml
set @variables = somehow select the subtree 'Variables' from xmlIndata;

Then @variables should be:
 ' <Variables>
    <Variable>
      <Name>N05C</Name>
    </Variable>
    <Variable>
      <Name>N06A</Name>
    </Variable>
    <Variable>
      <Name>PeopleCount</Name>
    </Variable>
  </Variables>'

Open in new window

seems pretty basic to be able to extract part of an xml but i cant find out how to do it.
0
This works:

const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");

const MONGODB_URI =
  "mongodb+srv://username:password@brucegust-wxyz.mongodb.net/applied";

app.get("/api", (req, res) => {
  //console.log("hello");
  res.json({
    message: "Welcome to the API"
  });
});

app.post("/api/posts", verifyToken, (req, res) => {
  jwt.verify(req.token, "secretkey", (err, authData) => {
    if (err) {
      res.sendStatus(403);
    } else {
      res.json({
        message: "Post created",
        authData
      });
    }
  });
});

app.post("/api/login", (req, res) => {
  //Mock User
  const user = {
    id: 1,
    username: "brad",
    email: "email@domain.com"
  };

  jwt.sign({ user: user }, "secretkey", { expiresIn: "30s" }, (err, token) => {
    res.json({
      token: token
    });
    console.log("yes");
  });
});

// format of Token
// Authorization: Bearer <access_token>

//verify Token

function verifyToken(req, res, next) {
  //get auth header value
  const bearerHeader = req.headers["authorization"];
  // check if bearer is undefined
  if (typeof bearerHeader !== "undefined") {
    // split at the space
    const bearer = bearerHeader.split(" ");
    //get token from array
    const bearerToken = bearer[1];
    console.log(bearerToken);
    

Open in new window

0
HI this is a continuation of thread from before
old thread

the conditions for this project has changed a little rendering the script that Michelangelo had provided no longer useful for my cause although it worked for the previous purpose

heres what changed:
the files in questions are XML format (but are not named .xml they are .901 files)
i need to remove a whole node from the *.xml files ,  including the tag

i.e.
 <errsql yadadayda > 
random sql error the statement has terminated
</errsql>

this whole line need to be removed form the file

here is a snippet of the xml file:

<chgsql ts="07:01:58.971" op="O" jb="ADD" tb="CLL_TAB" sc="BATCH"> <fld fd="F1000" af="PAL"/>
<fld fd="F1148" af="43000135163"/>
<idx fd="F1577" af="5167599565"/>
<idx fd="F1578" af="LINK"/>
<fld fd="F1001" af="1"/>
<fld fd="F902" af="00003814"/>
</chgsql>
<errsql ts="07:01:58.986" op="O" lv="50" ob="">
<sql>INSERT INTO CLL_TAB [F1000,F1148,F1577,F1578,F1001,F902] VALUES [:F1000,:F1148,:F1577,:F1578,:F1001,:F902] </sql>
<prm>PAL,43000135163,5167599565,LINK,1,00003814,</prm>
</errsql>
<chgsql ts="07:01:58.986" op="O" jb="ADD" tb="CLL_TAB" sc="BATCH">
<fld fd="F1000" af="PAL"/>
<fld fd="F1148" af="43000135164"/>
<idx fd="F1577" af="5166282554"/>
<idx fd="F1578" af="LINK"/>
<fld fd="F1001" af="1"/>
<fld fd="F902" af="00003814"/>
</chgsql>
0
I have been working towards creating a multiplayer three.js fps game and am planning to only do client-side prediction in the browser. On the other hand, I am using Node.js Express.js and Socket.io for the authoritative server-side implementation of the multiplayer game and would like to check collision server-side.

Using three.js or external libraries, what are the possible options to create a headless version of the game state like the babylon.js-nullengine and calculate raycasting collision on the server-side?

Similarly, how do three.js multiplayer io-based games keep track of game states server-side and do bullet and movement collision?
1
I have created a node.js API and use React to get data from the API and display it on the frontend. I however need to start doing some simple SEO work like titles and meta descriptions etc. but not sure how to do this.

I installed React Helmet and in Google console if I look at the elements I can see the title and description there but I don't think that is enough to show up for search engines?

          <Helmet>
            <title>My page title</title>
            <meta name="description" content="Helmet application" />
          </Helmet>

Open in new window

0
structure
I am attempting to render a view through the template engine "handlebars" for node.js with the express framework. Please see attached my file structure.  After running the route below, I keep receiving the following error: [Error: Failed to lookup view "layout" in views directory "C:\Users\frontstart\Dropbox\Web Design\nodetest\views"]. Can someone please help me locate my error.


router.get("/alldata", (req, res) =>
  Store.findAll()
    .then(stores => {
        path is //views/gigs.handlebars
        res.render('gigs', {
              stores
        });
       })
    .catch(err => console.log(err)));

module.exports = router;

Here is the backend app.js

const fs = require("fs");
const express = require("express");
const expressSession = require("express-session");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const path = require("path");
const expressLayouts = require("express-ejs-layouts");
const mysql = require("mysql");
const mysql2 = require("mysql2");
const multer = require("multer");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const Joi = require("@hapi/joi");
const connectFlash = require("connect-flash");
const morgan = require("morgan");
const passport = require("passport");
const passportLocal = require("passport-local");
const Sequelize = require("sequelize");
const db = require("./middleware/db.js");
const 

Open in new window

0
Fundamentals of JavaScript
LVL 13
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

I am using  Joi (Happy) module in node.js to validate entries into a form to a mysql database.  However, the validation does not work. I am receiving a "TypeError: Cannot read property 'path' of undefined" every time I leave the file field empty.  Nothing occurs when I leave any other field empty.  In other words, the validation simply does not work and no field message is being sent to the user based on the entry criteria. Please see the backend and the frontend code using sequelize. Without validation, the form works fine.

FRONTEND CODE WITH FORM:

<!DOCTYPE html>
<html lang="en">
<head>
  <!--JQuery UI: default css (smoothness)(always first)-->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> 


  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <!--JQuery (always first)-->
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>

<!--JQuery UI core (always first)-->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<!--JQuery UI(after JQuery UI core) - Controls Dialog Modal -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 

</head>
<body>
  <!---(8)-->
  <h3>Inserting Data into the database</h3>
  <h3>Data List</h3>
  <div id="storesF">
  <div 

Open in new window

0
I've been asked to write an Open API with the end result being an Authentication Microservice that authenticates an incoming JWT and allows it to engage in an ETL transaction between HealthKit and our database.

My piece of the project doesn't involve having to knock on HealthKit's door. Rather, Healthkit / the user is knocking on mine.

At this point, I'm in the shallow end of the pool. I'm just now getting my feet wet with Node so I'm still learning terms and concepts and while I'm surrounded by some very talented and approachable co-workers and supervisors, I wanted to leverage the collective wisdom of EE to at least have an idea of where I need to start so I can have some intelligent questions to ask when I head in to work tomorrow.

What I want to do with this question is give you an overview of what I understand and how to proceed. In some cases, I'm not even sure how to start, but that's how you learn.

Here we go...

To write my Open API, the editor that was recommended was https://www.apicur.io/. How does one start? From what I understand, it's code agnostic and I'm just documenting what equates to systemic scaffolding so that the end result is a document that explains how things are going to be captured and processed.

Feel free to weigh in at any time...

The next thing that I plan on doing is finding out the substance of the incoming JWT - specifically what's in the payload and how I need to parse that out so I can validate it in the context of the …
0
Installed node version: v10.16.2
               npm version: 6.10.3

When i run the command 'npm install -g'

Got the below error.

npm ERR! code ENOENT
npm ERR! syscall rename
npm ERR! path /Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/Newton-7c7da797/node_modules/@babel/code-frame
npm ERR! dest /Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/@babel/code-frame-bbf22dc8
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, rename '/Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/Newton-7c7da797/node_modules/@babel/code-frame' -> '/Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/@babel/code-frame-bbf22dc8'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/sdatla/.npm/_logs/2019-08-19T14_43_17_871Z-debug.log

Please help
0
I have manually updated package.json file on my local directory.

I did npm install globally using the below command.

npm install npm@latest -g

It created a package.json file from the install. Is there a way to point package.json from my local directory?
0
I was in a meeting today with my co-workers where our boss announced that we're going to start building out a project in Node.

I've been going through a Node Tutorial and I've made a point of taking thorough notes, but there were some terms being thrown around in the meeting and I have them below. I'm taking a crack at defining them, but I wanted some other eyes on this so I can both sound intelligent and begin working in a way that's sound.

First, what is an ETL? I was looking at this article, but I've not run into this before. Here's the link: https://blog.panoply.io/6-top-level-etl-tools-for-node.js-and-2-paid-etls

Throughout the meeting, the phrase "spec it out" was used. I'm assuming that refers to documenting what it is that needs to be done after having analyzed the job, correct?

Data Point - another term that was being thrown around. After looking it up, it looks as though a data point is a piece of information. A last name could be a data point, correct?

Swagger - the project I'm working is grabbing info from Mac's Healthkit and making it available in our company's application. An API is going to be part of the process, obviously, and I get the impression that Swagger is a part of the process. How? (https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b)

Stoplight - seems like this is similar to Swagger. What is it and what is its function?

FHIR - I'm reading through this article: …
0
I would like to select a record from a mysql database by "id" using sequelize.  I currently can do it with a mysql query and it works but I am receiving a null result when attempting to do it in sequelize.  Here is the query in my mysql which works and the query in sequelize which does not work. What am I doing wrong with the syntax in the sequelize version?




``````````````````````````````````````````````````````````````````````````````
        (1)

        router.get("/station/number/:id", (req, res) => {
      db.query(
            "SELECT * FROM stores WHERE id = ?",
            [req.params.id],
            (err, rows, fields) => {
                  if (!err) res.send(rows);
                  else console.log(err);
            }
      );
});


       (2)
 
      router.get("/station/number/:id", (req, res) =>

      Store.findOne ({
      where: {id:'?'}})
      .then(data=>{
     res.send({stores:data})
      })
     .catch(err => console.log(err)));
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
>