by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jun 02 06:16
    @ljharb banned @frank-dspeed
  • Apr 27 2018 01:23
    @MylesBorins banned @fjeddy
  • Feb 24 2016 08:26
    @rvagg banned @jonathanenbe
Brian Crowder
@crowder
@ljharb Don't suppose you've any hints, in the meantime?
Jordan Harband
@ljharb
only to prefer pure js modules :-)
Liviu Lupei
@liviulupei
Hi everyone, I'm working in the team who created Endtest.
I've dealt with all the possible corner cases for testing NodeJS apps, I've join this channel to help others.
https://endtest.io
TamashiKaizenカイゼン
@TamashiKaizen
Jordan Harband
@ljharb
class extends Error { get name() { return ‘custom’; } }?
TamashiKaizenカイゼン
@TamashiKaizen
@ljharb Hi, it seems like the name cannot be retrieved using custom class method.
TypeError: err.getName is not a function`
class AppError extends Error {
    constructor(message, statusCode){
        super(message);

        this.statusCode = statusCode;
        this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';        
        this.isOperational = true;        

        Error.captureStackTrace(this, this.constructor);
    }

    setName(name) {
        this.name = name;
    }
    getName(){
        return this.name;
    }
}

module.exports = AppError;
Jordan Harband
@ljharb
not .getName. get name - a property getter
get name() {} means that new AppError().name will call that function
you could also do AppError.prototype.name = ‘AppError’, which would be better.
TamashiKaizenカイゼン
@TamashiKaizen
@ljharb sorry i don't quite understand the get name() {} function.
Can you send an example code?
@ljharb If i use AppError.prototype.name = ‘AppError’, will it affect the prototype.name of other natural errors?
@ljharb It seems like the errorHandler can only retrieve the name of the natural errors, but not for custom error name appended and manually thrown.
Jordan Harband
@ljharb
i already sent the example code. verbatim.
and no, it won't affect other erros
AppError.prototype is only for AppErrors.
TamashiKaizenカイゼン
@TamashiKaizen
@ljharb should i use throw instead? The error.name value does appear in centralErrorHandler but i'm not sure if using throw err; is correct.
if (!errors.isEmpty()) {
        let err = new AppError(`Invalid login credentials.`, 422);
        err.name = 'ExpressValidatorError';            

       throw err;
      }
Jordan Harband
@ljharb
you should, but that's not related to the name
you should probably set the name in the constructor tho
TamashiKaizenカイゼン
@TamashiKaizen
@ljharb thank you :)
@ljharb what is the difference of return next(err); and throw err; ?
Jordan Harband
@ljharb
oh, you didn’t say it was in an express middleware
yes definitely return next(err)
the difference is that throw doesn’t work async unless it’s in a promise.
TamashiKaizenカイゼン
@TamashiKaizen
@ljharb ohh i see, thank you
TamashiKaizenカイゼン
@TamashiKaizen
@ljharb i changed the AppError class to this, but don't know why the error.name passed to the errorHandler still console logs as undefined
class AppError extends Error {
    constructor(name, statusCode, message){
        super(message);

        this.name = name;
        this.statusCode = statusCode;
        this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';        
        this.isOperational = true;                   

        Error.captureStackTrace(this, this.constructor);
    }              
}

module.exports = AppError;
if (!errors.isEmpty()) {
        console.log(errors.array());
        let err = new AppError('ExpressValidatorError', 422, 'Invalid login credentials.');                     
        return next(err);
      }
errorHandler.js
module.exports = (err, req, res, next) => {        
    err.statusCode = err.statusCode || 500;
    err.status = err.status || 'error';    


        let error = {...err};             

        console.log(error.name);

        if(error.name === 'ExpressValidatorError') error = handleExpressValidatorError(error);

        if(error.name === 'InternalOAuthError') error = handleInternalOAuthError(error);


}
Mile Mijatović
@mijatovicmile
Hello
I have Node.js Code assignment challenge
Since getting the conversion rate is a long and CPU consuming task (for the sake of this
assignment of course) and the company only allows you to buy up to 2 small cloud instances,
you let the company know that it will be best to defer the user requests and email the results
back to them once it is ready (in a reasonable amount of time).
Assumptions:
- Create a dummy async function that will send the email, no need to actually send it
Please advice me , what's the best solution to achieve that ?
with Node.js
@ljharb
Ibrahim Hussein
@DevIbrahimHussein
 // save to database
    newCategory.save()
    .then(category => {

        // add category to family
        Family.findOneAndUpdate(category.family,function(err,family){
            if(err) return res.send(err);
            family.categories.push(category.id)
            family.save(function(err,fam){
                if(err) return res.send(err);
                res.send(fam);
            })
        })

        res.send(category);
    }).catch(err => {
        res.status(500).send({
            message: err.message || "Some error occured"
        })
    })

problem

not added to categories in family schema

Schema

const FamilySchema = new Schema({
    title: {
        type: String,
        require: true
    },
    categories: [
        {
            type: Schema.Types.ObjectId,
            ref: Category
        }
    ]
});
poonam20nikam
@poonam20nikam
HI
Sidharth-Bansal
@Sidharth-Bansal
How to handle redirects fired from node to display specific screens in the react native?
vivekweb2013
@vivekweb2013
https://github.com/vivekweb2013/toastmaker - small & useful npm module for showing toast
feedback is most welcome
Praveen Durairaju
@praveenweb
Hi Folks,
I just wrote a tutorial to convert any Node.js REST API to GraphQL using Hasura.
https://hasura.io/blog/turn-your-node-js-rest-api-to-graphql/
Open to feedback :)
sgda021992
@sgda021992
anyone familiar with nestjs
sgda021992
@sgda021992
i have a app module in which i have imported a module
say i have a app module in which i have imported auth module
and in auth module i have imported client module and jwt module
and in providers i have a service
Amit Sahoo
@Amiit006

Hi Folks,
I have one application developed in Spring with CORS configuration
when I use ajax call it works fine and prevent to fetch the data. But in node its not working.
Ajax Code

$(document).ready(function() {
    $.ajax({
        url: "http://localhost:8085/greeting",
    }).then(function(data, status, jqxhr) {
       $('.greeting-id').append(data.id);
       $('.greeting-content').append(data.content);
       console.log(jqxhr);
    });
 });

Node Code:

server.get('/node', (request, response) => {
    const reqGet = http.get('http://localhost:8085/greeting', (res) => {
        let data = '';
        res.on('data', (chunk) => data += chunk);

        res.on('end', () => console.log(data));
    }).on('error', (err) => console.log(err));

    response.status(200).send("hello");
});

I am no expert in both of these things. Its just a simple application to check CORS working or not.
Expected Result:
Access to XMLHttpRequest at 'http://localhost:8085/greeting' from origin 'http://localhost:9001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please advise

Vaibhav Shrivastava
@mishuvs
Hi everyone, does anyone know why we use cookie-session along with passport.js? Here's the stack overflow question:
https://stackoverflow.com/questions/62894933/why-use-cookie-session-in-addition-to-passport-js
TamashiKaizenカイゼン
@TamashiKaizen

Hi, is there a difference on passing to req.query vs req.body in terms of security? I'm not sure which one to use to pass a mobile number to server to trigger sms one time pin.

req.query

axios.post('sendOneTimePin', {
    params: {
        mobileNumber: '+12345678910'
    } 
});

req.body

axios.post('sendOneTimePin', {
    data: {
        mobileNumber: '+12345678910'
    } 
});
Sidharth-Bansal
@Sidharth-Bansal

@Sidharth-Bansal
Do you know how shall i get the value of /login or /signup in the authentication.js from the app.js file?

const express = require("express");
const session = require("express-session");
const redis = require("redis");
const redisStore = require("connect-redis")(session);
const client = redis.createClient();
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const TWO_MINUTE = 1000 * 60 * 2;
const {
  NODE_ENVIRONMENT = "development",
  SESSION_NAME = "SID",
  HOST = "localhost",
  PORT = 6379,
  TTL = 260,
  SESSION_SECRET = "gamezySecretsNeverRevealed",
  SESSION_LIFETIME = TWO_MINUTE,
} = process.env;
const IN_PROD = NODE_ENVIRONMENT === "production";
app.use(
  session({
    name: SESSION_NAME,
    store: new redisStore({
      host: HOST,
      port: PORT,
      client: client,
      ttl: TTL,
    }),
    secret: SESSION_SECRET,
    saveUninitialized: false,
    resave: false,
    cookie: {
      maxAge: SESSION_LIFETIME,
      sameSite: true,
      secure: IN_PROD,
    },
  })
);
const homeRoutes = require("./api/routes/home");
const authenticationRoutes = require("./api/routes/authentication");

// Logger
app.use(morgan("dev"));

// Parsing the incoming data
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Routes which handle requests
app.use("/login", authenticationRoutes);
app.use("/signup", authenticationRoutes);
app.use("/home", homeRoutes);
module.exports = app;

this is app.js

const express = require("express");
const router = express.Router();
const fetch = require("node-fetch");
const app = require("../../app");
var url = "http://192.168.43.106:9090/" + ?;
var headers = {
  "Content-Type": "application/json"
};
const redirectHome = (req, res, next) => {
  if (req.session.username) {
    res.status(302).send("Home");
  } else {
    next();
  }
};
router.post("/", redirectHome, (req, res, next) => {
  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      username: req.body.username,
      password: req.body.password,
    }),
  })
    .then((response) => {
      res.status(response.status);
      if (response.status === 200) {
        req.session.username = req.body.username;
      }
      return response.text();
    })
    .then((text) => {
      res.json(text);
    })
    .catch((error) => {
      console.log("-----error----");
      console.log(error);
      console.log("-----error----");
      next(error);
    });
});

module.exports = router;

this is authentication.js

Mile Mijatović
@mijatovicmile
Hello
I have mongoose question , I hope someone can help me
const mongoose = require("mongoose");

const config = require("./config");

// MongoDB URI
const mongoURI =
  "mongodb+srv//" +
  config.mongo.user +
  ":" +
  config.mongo.password +
  config.mongo.host +
  config.mongo.authDB +
  "?retryWrites=true&w=majority";

console.log(mongoURI);

// Connect to MongoDB Cluster
mongoose
  .connect(mongoURI, { useNewUrlParser: true })
  // Successfully connected to database
  .then(() => {
    console.log("Successfully connected to MongoDB");
  })
  // Catch any potential error
  .catch((err) => {
    console.log("Unable to connect to MongoDB. Error: " + err.message);
    process.exit(1);
  });