當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript cors.default函數代碼示例

本文整理匯總了TypeScript中cors.default函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript default函數的具體用法?TypeScript default怎麽用?TypeScript default使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了default函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: server

export default function server(session: any): express.Express {

	// Init server
	const app: express.Express = express();
	app.disable('x-powered-by');

	app.use(bodyParser.urlencoded({ extended: true }));
	app.use(cookieParser(config.cookiePass));

	// Session settings
	app.use(expressSession(session));

	// CSRF
	app.use(csrf({
		cookie: false
	}));

	// CORS
	app.use(cors({
		origin: true,
		credentials: true
	}));

	app.use((req, res, next) => {
		res.header('X-Frame-Options', 'DENY');
		next();
	});

	router(app);

	return app;
}
開發者ID:armchair-philosophy,項目名稱:Misskey-Web,代碼行數:32,代碼來源:server.ts

示例2: server

export default function server(): express.Express {

	// Init server
	const app: express.Express = express();
	app.disable('x-powered-by');

	// CORS
	app.use(cors({
		origin: true,
		credentials: false
	}));

	// SVGZ
	// see: https://github.com/strongloop/express/issues/1911
	app.get(/.svgz/, (req, res, next) => {
		res.set({'Content-Encoding': 'gzip'});
		next();
	});

	app.use(express.static(`${__dirname}/resources`));

	// Not found handling
	app.use((req, res) => {
		res.status(404).send('not-found');
	});

	return app;
}
開發者ID:armchair-philosophy,項目名稱:Misskey-Web,代碼行數:28,代碼來源:resources-server.ts

示例3: runServer

function runServer(schemaIDL: Source, extensionIDL: Source, optionsCB) {
  const app = express();

  if (extensionIDL) {
    const schema = buildServerSchema(schemaIDL);
    extensionIDL.body = extensionIDL.body.replace('<RootTypeName>', schema.getQueryType().name);
  }
  app.options('/graphql', cors(corsOptions))
  app.use('/graphql', cors(corsOptions), graphqlHTTP(() => {
    const schema = buildServerSchema(schemaIDL);

    return {
      ...optionsCB(schema, extensionIDL),
      graphiql: true,
    };
  }));

  app.get('/user-idl', (_, res) => {
    res.status(200).json({
      schemaIDL: schemaIDL.body,
      extensionIDL: extensionIDL && extensionIDL.body,
    });
  });

  app.use('/user-idl', bodyParser.text());

  app.post('/user-idl', (req, res) => {
    try {
      if (extensionIDL === null)
        schemaIDL = saveIDL(req.body);
      else
        extensionIDL = saveIDL(req.body);

      res.status(200).send('ok');
    } catch(err) {
      res.status(500).send(err.message)
    }
  });

  app.use('/editor', express.static(path.join(__dirname, 'editor')));

  app.listen(argv.port);

  log(`\n${chalk.green('✔')} Your GraphQL Fake API is ready to use 🚀
  Here are your links:

  ${chalk.blue('❯')} Interactive Editor:\t http://localhost:${argv.port}/editor
  ${chalk.blue('❯')} GraphQL API:\t http://localhost:${argv.port}/graphql

  `);

  if (!fileArg) {
    log(chalk.yellow(`Default file ${chalk.magenta(fileName)} is used. ` +
    `Specify [file] parameter to change.`));
  }

  if (argv.open) {
    setTimeout(() => opn(`http://localhost:${argv.port}/editor`), 500);
  }
}
開發者ID:codeaudit,項目名稱:graphql-faker,代碼行數:60,代碼來源:index.ts

示例4: initialize

    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------

    /**
     * Initializes the things driver needs before routes and middlewares registration.
     */
    initialize() {
        if (this.cors) {
            const cors = require("cors");
            if (this.cors === true) {
                this.express.use(cors());
            } else {
                this.express.use(cors(this.cors));
            }
        }
    }
開發者ID:MrDataScientist,項目名稱:routing-controllers,代碼行數:17,代碼來源:ExpressDriver.ts

示例5: config

  private config() {

    const app = this.app;
    const port = this.normalizePort(process.env.PORT || this.port);

    // set server port
    app.set('port', port);
    // view engine setup
    app.set('views', path.join(__dirname, '/views'));
    app.set('view engine', 'jade');
    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger(this.logLevel));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
      extended: false
    }));
    app.use(cookieParser());
    app.use(cors());
    app.use(express.static(path.resolve(__dirname + '/client/statics')));
    if (process.env.NODE_ENV === 'development') {
      // only use in development
      app.use(errorhandler({
        log: (err, str, req) => this.errorNotification(err, str, req)
      }));
    }
  }
開發者ID:thehachez,項目名稱:maduk,代碼行數:27,代碼來源:app.ts

示例6: configExpressServer

    private configExpressServer() {
        this.app.use(helmet({
            noCache: true,
            referrerPolicy: true
        }));
        // todo CHANGE origin in production mode based on your requirement
        this.app.use(cors({
            origin: [/https?:\/\/*:*/],
            methods: ['GET', 'POST', 'PUT', 'DELETE'],
            allowedHeaders: ['X-Requested-With', 'Content-Type', 'Content-Length', 'X-Auth-Token', 'X-Auth-User'],
            exposedHeaders: ['Content-Type', 'Content-Length', 'X-Auth-Token']
        }));
        this.app.use(loggerMiddleware);
        this.app.use(morgan(this.setting.env == 'development' ? 'dev' : 'combined'));
        this.app.use(bodyParser.urlencoded({limit: '50mb', extended: false}));
        this.app.use(bodyParser.json({limit: '50mb'}));
        // closing connection after sending response ???
        this.app.use((req: IExtRequest, res: express.Response, next: express.NextFunction) => {
            res.set('Connection', 'Close');
            next();
        });

        this.app.enable('trust proxy');
        this.app.disable('case sensitive routing');
        this.app.disable('strict routing');
        this.app.disable('x-powered-by');
        this.app.disable('etag');
    }
開發者ID:VestaRayanAfzar,項目名稱:express-api-template,代碼行數:28,代碼來源:ServerApp.ts

示例7: cors

module.exports.cors = function(options){
  options = options || {}
  options.maxAge = options.maxAge==null ? 3000 : options.maxAge//prevent subsequent OPTIONS requests via cache
  options.exposedHeaders=options.exposedHeaders||safeHeaders
  options.allowedHeaders=options.allowedHeaders||safeHeaders
  return cors(options)
}
開發者ID:AckerApple,項目名稱:ack-node,代碼行數:7,代碼來源:router.ts

示例8: function

mongoose.connection.on('open', function () {
 
    console.error('mongo is open');
    var app = express();
    app.use(cors());
    app.use(cors());
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());
 	app.use('/app', express.static(path.resolve(__dirname, 'app')));
	app.use('/vendor', express.static(path.resolve(__dirname, 'vendor')));
	var photos = require('../server/routes/photos.js')(app);
	var users = require('../server/routes/users.js')(app);

    app.listen(3000, function (err) {
    console.log('This express app is listening on port: 3000');
    });
 
});
開發者ID:jrothrock,項目名稱:dosplash,代碼行數:18,代碼來源:server.ts

示例9: next

swaggerExpress.create(swaggerConfig, function (err, swagger) {
  if (err) { throw err; }


  app.use(function (req, res, next) {
    next();
  });

  app.use(cors(corsOptions));
  swagger.register(app);

  app.get(
    '/auth/google',
    passport.authenticate('google', {
      session: false,
      scope: [
        'https://www.googleapis.com/auth/userinfo.profile',
        'https://www.googleapis.com/auth/userinfo.email',
      ],
    }),
  );

  app.get('/auth/google/callback',
    function (req, res, next) {
      passport.authenticate('google', {
        session: false,
        failureRedirect: api.helpers.Config.settings.ui_base_path,
      },
        function (error, user: api.models.UserModel, info) {
          if (error) { return next(error); }
          if (!user) { return res.redirect(api.helpers.Config.settings.ui_base_path); }
          try {
            let token = jwtService.signToken(user);
            // to prevent from csrf attack we sent back a XSRF-TOKEN in a cookie
            res.cookie('XSRF-TOKEN', token.xsrf, { maxAge: 900000, httpOnly: false });
            res.cookie('JWT-TOKEN', token.jwt, { maxAge: 900000, httpOnly: true });
            let isAdmin = 'false';
            if (user.roles && user.roles.indexOf('admin') > -1) {
              isAdmin = 'true';
            }
            return res.redirect(`${api.helpers.Config.settings.ui_base_path}/#/login?user_id=${user.id}&is_admin=${isAdmin}`);
          } catch (err) {
            return next(err);
          }
        })(req, res, next);
    });

  app.listen(port);

  if (swagger.runner.swagger.paths['/hello']) {
    console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
  }
});
開發者ID:arandehkharghani,項目名稱:tforex-gateway,代碼行數:53,代碼來源:app.ts

示例10: makeHttpServer

export function makeHttpServer(config: Config) {
  const app = express()
  const server = new AdminAPI(config)

  app.use(expressWinston.logger({
    winstonInstance: logger
  }))

  app.use(cors())
  
  app.post(/\/v1\/admin\/reload/, (req: express.Request, res: express.Response) => {
    return server.checkAuthorization(req.headers['authorization'])
      .then((authResult) => {
        if (!authResult) {
          return { statusCode: 403, status: { error: 'forbidden' } }
        }
        
        return server.handleReload()
      })
      .then(reloadStatus => writeResponse(res, reloadStatus.status, reloadStatus.statusCode))
  })

  app.get(/\/v1\/admin\/config/, (req: express.Request, res: express.Response) => {
    return server.checkAuthorization(req.headers['authorization'])
      .then((authResult) => {
        if (!authResult) {
          return { statusCode: 403, status: { error: 'forbidden' } }
        }

        return server.handleGetConfig()
      })
      .then((configData) => writeResponse(res, configData.status, configData.statusCode))
  })

  app.post(
    /\/v1\/admin\/config/, express.json(),
    (req: express.Request, res: express.Response) => {
      return server.checkAuthorization(req.headers['authorization'])
        .then((authResult) => {
          if (!authResult) {
            return { statusCode: 403, status: { error: 'forbidden' } }
          }

          const newConfig = req.body
          return server.handleSetConfig(newConfig)
        })
        .then((configStatus) => writeResponse(res, configStatus.status, configStatus.statusCode))
    })

  return app
}
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:51,代碼來源:http.ts


注:本文中的cors.default函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。