Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
    @bigbigDreamer 太感謝你了~

    Hi I have an index.html which is getting served by express server thru https, now if I need to access other API's with a different domain, I see cors issues, even though the API has the Access-Control-Allow-Origin as * and coming as "https://localhost:3000" in the OPTIONS request, but the main POST is failing with

    Access to fetch at 'https://blahblah/Api/search/v1/describe?resources=order' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

    this is my start-server script

    const startServer = function() {
      var privateKey  = fse.readFileSync('build-config/ssl/key.pem', 'utf8');
      var certificate = fse.readFileSync('build-config/ssl/cert.pem', 'utf8');
      var credentials = {key: privateKey, cert: certificate};
      const PORT = BUILD_CONFIG.deploy.port;
      const HOST = '';
      const app = express();
      // const corsOptions = {
      //   origin: function(origin, callback) {
      //     callback(null, true);
      //   },
      //   credentials: true,
      // };
      app.use(function(req, res, next) {
        const indexHtml = 'index.html';
        let { url } = req;
        // console.log(url);
        const queryIndex = url.indexOf('?');
        if (queryIndex > 0) {
          url = url.substring(0, queryIndex);
        if (url.endsWith(indexHtml) || url.endsWith('/')) {
          if (!url.endsWith(indexHtml)) {
            url += indexHtml;
          sendIndex(url, req, res, next);
        } else {
      // const server =
      // app.listen(PORT, () => {
      //   open(`http://localhost:${PORT}`);
      // });
      var httpsServer = https.createServer(credentials, app);
      httpsServer.listen(PORT, HOST, function() {
        console.log(`app listening on localhost port: ${PORT}`);
    2 replies
    Bruno Louzada
    Guys I need to handle users session expiration when an session expire I need to send analytics data for example, my approach today is to use redis as session store, overwrite genid function and user username as session id, the problem is users using same username, I should use this approach with an random part in session id or use another approach?
    Sourabh Grover
    Is there any way to get number of sheets in excel file in xlsx(https://www.npmjs.com/package/xlsx) package ?
    I am coming from PHP background. How can I store application level parameters in express and how can I access that? Example parameters like third party API keys, different model status values etc
    How are you?
    We are working on app with express. is is a good/bad practice to add property to request object, as we need things to be scoped
    (I have a stackoverflow thread)
    What do you think?
    @stefdelec You can try aex. a scoped web server compatible with express middleware
    Fedor Pasynkov
    Hi colleagues
    Diogo Pina Serra
    Hey there anyone could help me with the express-validator ?

    I have a post with a json like :

      callid: 1335,
      AgentExtension: '1998',
      origin: [
          ClientName: 'Julio Manuel',
          ClientCode: '1334',
          ClientNumber: 35196666666
          ClientName: 'Manuel Luis',
          ClientCode: '2220',
          ClientNumber: 351914444444
          ClientName: 'Diogo Serra',
          ClientCode: '9999',
          ClientNumber: 351212345678

    and i'm checking if the ClientNumber exists and is Numeric with other checks:

    const validations = [

    But it is returning

      errors: [
          value: undefined,
          msg: 'Invalid value',
          param: 'origin..ClientNumber',
          location: 'body'
          value: undefined,
          msg: 'Invalid value',
          param: 'origin..ClientNumber',
          location: 'body'
    Diogo Pina Serra
    Is it because i have multiple arrays on the JSON ... hmmmm checking if with just one it pass .
    Hmm no it returned again 2 errors (so i believe it is the exist and Numeric checking both are failing).... how do i check inside the arrays ?
    Diogo Pina Serra
    Ok Found the problem ... it was always on my eyes "value: undefined"....
    Hi! is anyone explain csrf tokens using mean stack application. I am getting error in angular. 'inavlid csrf token' but I think there is an error in express (backend code)
    John Smeeth
    hi all
    Abu Syeed Sajid Ahmed

    const puppeteer = require('puppeteer');
    const request=require('request');
    const cheerio=require('cheerio')
    var newsModel=require('./NewsModel')
    var EventEmitter = require('events')
    var ee = new EventEmitter()

    class ScrapModel
    static websiteURL='https://www.nytimes.com';
    static options={};
    static browser;
    static posts;
    /*ee.on('message', function (text) {

      //10 sec interval
          ee.emit('message', 'hello world');
    static async proxyGenerator()
        let ip_addresses = [];
        let port_numbers = [];
        let proxy;
         request("https://sslproxies.org/", function(error, response, html) {
          if (!error && response.statusCode == 200) {
            const $ = cheerio.load(html);
            $("td:nth-child(1)").each(function(index, value) {
              ip_addresses[index] = $(this).text();
            $("td:nth-child(2)").each(function(index, value) {
              port_numbers[index] = $(this).text();
          } else {
            console.log("Error loading proxy, please try again");
          ip_addresses.join(", ");
          port_numbers.join(", ");
          //console.log("IP Addresses:", ip_addresses);
          //console.log("Port Numbers:", port_numbers);
          let random_number = Math.floor(Math.random() * 100);
          proxy = 'http://'+ip_addresses[random_number]+':'+port_numbers[random_number];
          return proxy;
    static async listenNewsUpdate()
        var proxy= await ScrapModel.proxyGenerator();
        ScrapModel.browser = await puppeteer.launch({
          headless: false,
          //args: [ '--proxy-server='+proxy ],
        const page = await ScrapModel.browser.newPage();
        await page.goto(ScrapModel.websiteURL);
        var posts= await page.evaluate(() => new Promise((resolve) => {
          var scrollTop = -1;
          const interval = setInterval(() => {
            window.scrollBy(0, 500);
            if(document.documentElement.scrollTop !== scrollTop) {
              scrollTop = document.documentElement.scrollTop;
            var posts=document.body.querySelectorAll('article')
            return posts;
          }, 10);
        var postItems=[];    
                'title': title,
                'links': link,
                'summery': summery
        await ScrapModel.browser.close();
        var news=new newsModel.NewsModel();
    static preprocess()
        //adding website url to the links in which website url are missing
        ScrapModel.articles.forEach(element => {
              var link=element['links'];
                  element['links']= ScrapModel.websiteURL+link;


    I am try to scrap all of the data of this site using above code.But I am getting undefined error on posts.foreach() line.Can anyone help me plzz :(

    @Sajid576 no
    Is it related to express?
    Abu Syeed Sajid Ahmed
    I am trying to scrape data using the express server...
    import { http } from "@aex/core";
    class User {
      @http("get", ["/profile", "/home"])
      profile(req, res, scope) {}
      @http(["get", "post"], "/user/login")
      login(req, res, scope) {}
      @http("post", "/user/logout")
      logout(req, res, scope) {}
    import { Aex, Router, http } from "@aex/core";
    class HelloAex {
      @http("*", "*")
      public all(_req: any, res: any, _scope: any) {
        res.end("Hello Aex!");
    const aex = new Aex();
    const hello = new HelloAex();
    Timo Myyrä
    hi, i'm upgrading our project but I've got odd issue with multer middleware. During jest tests it multer seems to upload file, req.files lists file info but there doesn't seem to be any files on file system
    the jest tests use mockfs to create dir tree and test files on file system and I see the test file and upload directory but not the uploaded file
    any idea what could cause multer to report missing file?
    Hello everyone!
    I'm new to developing web apps. I went through the express documentation. But I still don't feel confident about writing any apps. I want to focus on making APIs. What would be your advice for someone like me ?. I don't know if this is the right place to post something like this, let me know if so.
    Thanks in advance.
    joana canonigo
    Hello everyone! does anyone knows how to resolve the localhost:5000 cannot / get?
    hope somebody can help me
    I am trying to implement csrf in express and using Angular SPA but it shows error of
    "ForbiddenError: invalid csrf token"
    Here is the code
    const express = require("express");
    const bodyParser = require("body-parser");
    const cors = require("cors");
    const app = express();
    var cookieParser = require('cookie-parser')
    var csrf = require('csurf')
    var corsOptions = {
      origin: "http://localhost:8081"
    app.use(csrf({ cookie: true }))
    app.all('*', function (req, res,next) {
      res.cookie('XSRF-TOKEN', req.csrfToken())
      // res.render('index')
    // parse requests of content-type - application/json
    // parse requests of content-type - application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));
    const db = require("./app/models");
    // // drop the table if it already exists
    // db.sequelize.sync({ force: true }).then(() => {
    //   console.log("Drop and re-sync db.");
    // });
    // simple route
    app.get("/", (req, res) => {
      res.json({ message: "Welcome to bezkoder application." });
    // set port, listen for requests
    const PORT = process.env.PORT || 8080;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}.`);
    Hi there, can we use JWT instead of CSRF token. JWT can be work as CSRF tokens?
    Has anyone had success building an OAuth2 server?
    I'm using "express-oauth-server": "^2.0.0", but when I call return app.oauth.authorize(); the request hangs
    When I do post request I get error 'invalid csrf token'. can anyone help me? code is still same which I have posted as above
    Csrf —> cookie. Jwt --> req-header
    Julian Zhu
    In my option,jwt is better than csrf
    need to learn and tighten up on jwt

    @OrangeBorning I have this link but it is not working for me. in the above code

    app.all('*', function (req, res,next) {
      res.cookie('XSRF-TOKEN', req.csrfToken())
      // res.render('index')

    is not working I don't know where the problem is occuring

    Hi guys! I have found the solution.
    Please have a look at this npm module
    Jose Luis

    Hi guys, I'm starting with expressJs, my problem is that I'm creating a new route in my API, but it doesn't load the route gives me this error:

    {"errors":[{"path":"/api/v1/service/other", "message": "not found"}]}

    This is the code, as you can see it is identical to another endpoint that works (I have restarted the server)

    import express from 'express';
    import serviceController from './serviceController';
    export default express.Router()
      .get('/version', serviceController.getVersion)
      .get('/other', serviceController.getVersion)

    However, the other endpoint api/service/version does work correctly

    Steven Lee
    Hello, everyone! I am a full-stack developer with JavaScript frameworks. Does anyone have a project to give me for a job?
    Erik Snider

    In an mvc architecture, what are the advantages to separating routes and controllers? When I search online, I find lots of articles about how, but not why
    Keeping them together:

    router.get('/foo', middleware1, middleware2, function(req, res, next) {
      ... controller code that depends on the middlewares ...

    Separating them (probably in different files):

    // router file
    router.get('/foo', middleware1, middleware2, FooController.action)
    // controller file
    module.exports.action = function(req, res, next) {
      ... controller code that depends on the middlewares ...

    It seems like it might be difficult to keep track of which middlewares are installed for which routes / controller actions, if they're separated into different files. So, there must be some significant advantages, which overcome this potential downside.
    In this case, I'm using middleware1 and middleware2 similar to how you might use before_action in rails

    Nick Medrano
    @AlexLee-webdev I have a small app I'm building and may need some help. Contact me for details/
    Hello All
    What is the best excel library to work with for reading excel sheet data .xlsx in NodeJS ?