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


TypeScript cors類代碼示例

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


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

示例1: main

async function main() {
  const app = express();
  app.use(cors());

  await initAccounts();

  app.use(session({
    secret: 'grant',
    resave: true,
    saveUninitialized: true,
  }));

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

  const grant = new Grant(grantConfig);

  app.use(GRANT_PATH, grant);

  app.get(`${GRANT_PATH}/handle_facebook_callback`, function (req, res) {
    const accessToken = req.query.access_token;
    res.redirect(`${STATIC_SERVER}/login?service=facebook&access_token=${accessToken}`);
  });

  app.get(`${GRANT_PATH}/handle_google_callback`, function (req, res) {
    const accessToken = req.query.access_token;
    res.redirect(`${STATIC_SERVER}/login?service=google&access_token=${accessToken}`);
  });

  initializeOAuthResolver();

  const schema = createSchemeWithAccounts(AccountsServer);

  app.use('/graphql', bodyParser.json(), graphqlExpress(request => ({
    schema,
    context: JSAccountsContext(request),
    debug: true,
  })));

  app.use('/graphiql', graphiqlExpress({
    endpointURL: '/graphql',
  }));

  const server = createServer(app);

  new SubscriptionServer(
    {
      schema,
      execute,
      subscribe,
    },
    {
      path: WS_GQL_PATH,
      server,
    }
  );

  server.listen(PORT, () => {
    console.log('Mock server running on: ' + PORT);
  });
}
開發者ID:RocketChat,項目名稱:Rocket.Chat.PWA,代碼行數:60,代碼來源:index.ts

示例2: function

export let parserInit = ()=> {
    app.use(favicon(path.resolve('favicon.ico')));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));
    app.use(cookieParser());
    if (SERVER_CONFIG.env === DEV) {
        app.use(logger(DEV));
        var whitelist = ['http://127.0.0.1:3008','http://127.0.0.1:3006'];
        var corsOptionsDelegate = function(req, callback){
            var corsOptions;
            if(whitelist.indexOf(req.header('Origin')) !== -1){
                corsOptions = { origin: true ,credentials:true}; // reflect (enable) the requested origin in the CORS response
            }else{
                corsOptions = { origin: false }; // disable CORS for this request
            }
            callback(null, corsOptions); // callback expects two parameters: error and options
        };
        /*var corsOptions = {
            origin: 'http://127.0.0.1:3008',
            optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
        };*/
        app.use(cors(corsOptionsDelegate));//white List
        //app.options('http://127.0.0.1:3008', cors());//If allowed Access-Control-Allow-Origin:* Be sure to write
    }
    else if (SERVER_CONFIG.env === PROD) {
        app.use(logger('prod'));
    }
    timeoutParser.init();
    errParser.init();
    parserInit = ()=> {
        throw new Error("parsers/index.ts: parsers have been initialized.");
    }
}
開發者ID:guoyu07,項目名稱:react-node-cms,代碼行數:33,代碼來源:parserInit.ts

示例3: config

  /**
   * Configures application
   *
   * @class Server
   * @method config
   * @return {void}
   */
  public config(): void {
    // mount query string parser
    this.app.use(bodyParser.urlencoded({
      extended: true
    }))

    // mount json form parser
    this.app.use(bodyParser.json())

    // mount cookie parker
    this.app.use(cookieParser())

    // mount logger
    this.app.use(logger("dev"))
    
    // mount compression
    this.app.use(compression())
    
    // mount helmet
    this.app.use(helmet())
    
    // mount cors
    this.app.use(cors())

    // cors
    // this.app.use((req: Request, res: Response, next: NextFunction) => {
    //   res.header('Access-Control-Allow-Origin', 'http://localhost:8080')
    //   res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS, PURGE')
    //   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials')
    //   res.header('Access-Control-Allow-Credentials', 'true')
    //   next()
    // })
  }
開發者ID:yeegr,項目名稱:SingularJS,代碼行數:40,代碼來源:server.ts

示例4: bootstrap

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cors());
  app.useStaticAssets(join(__dirname, '..', 'public'));

  await app.listen(app.get(ConfigService).port);
}
開發者ID:mbechev,項目名稱:Feedback,代碼行數:7,代碼來源:main.ts

示例5: callback

server.setConfig((app) => {

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(morgan('combined'));
    app.use(cors({
        origin: (origin, callback) => {
            try {
                let ok: boolean = config.originsWhitelist.indexOf(origin) !== -1
                callback(null, ok);
            } catch (e) {
                callback(e, null);
            }

        }
    }));
    app.use(jwt({ secret: config.appSecret })
        .unless({
            path: ['/api/account/login', '/setup', '/',
                {
                    url: '/api/donors',
                    methods: ['GET', 'POST']
                }]
        }));

   let feed: DonorsFeed = kernel.get<DonorsFeed>(TYPES.DonorsFeed);
   feed.start(httpServer);
});
開發者ID:kibiluzbad,項目名稱:kamrusepa,代碼行數:28,代碼來源:server.ts

示例6: bootstrap

  public bootstrap(port: number) {
    // enable CORS
    this.expressApplication.use(cors(), (request: express.Request, response: express.Response, next: express.NextFunction) => {
        console.log("CORS enabled for all routes");
        next();
    });

    // configure API and error routes   
    this.expressContactRouter.configApiRoutes(this.expressApplication);
    this.expressContactRouter.configErrorRoutes(this.expressApplication);
    this.expressApplication.set("port", port);

    // create http server
    let server = http.createServer(this.expressApplication);
    server.listen(port);
    // add error handler
    server.on("error", onError);

    // start listening on port
    server.on("listening", onListening);

    // event listener for HTTP server "error" event.
    function onError(error: any) {
        "use strict";
        if (error.syscall !== "listen") {
            throw error;
        }

        let bind = typeof port === "string"
        ? "Pipe " + port
        : "Port " + port;

        // handle specific listen errors with friendly messages
        switch (error.code) {
        case "EACCES":
            console.error(bind + " requires elevated privileges");
            process.exit(1);
            break;
        case "EADDRINUSE":
            console.error(bind + " is already in use");
            process.exit(1);
            break;
        default:
            throw error;
        }
    }

    /**
     * Event listener for HTTP server "listening" event.
     */
    function onListening() {
        let addr = server.address();
        let bind = typeof addr === "string"
        ? "pipe " + addr
        : "port " + addr.port;
        let debugForExpress = debug("ExpressApplication");
        debugForExpress("Listening on " + bind);
    }
  }
開發者ID:rajajhansi,項目名稱:aspnetcore-aurelia-tutorial,代碼行數:59,代碼來源:express-application.ts

示例7: constructor

 constructor(options) {
     var corsOptions = {
         credentials: options.credentials || true,
         origin: options.origin || function(origin, callback) {
             callback(null, true);
         }
     };
     Container.get('app').use(cors(corsOptions));
 }
開發者ID:nicolanrizzo,項目名稱:node-microframework-cors,代碼行數:9,代碼來源:CorsPlugin.ts

示例8: constructor

  constructor() {
    this.app = express();

    this.app.use(cors());
    this.app.use(bodyParser.json());
    this.app.use(bodyParser.urlencoded({ extended: false }));

    this.setupSwagger();
    this.setupControllers();
  }
開發者ID:efueger,項目名稱:node-microservice-demo,代碼行數:10,代碼來源:Express.ts

示例9: registerCors

 private registerCors() {
     // Cors
     var corsOptions = {
         credentials: true,
         origin: function(origin, callback) {
             callback(null, true);
         }
     };
     this.app.use(cors(corsOptions));
 }
開發者ID:nicolanrizzo,項目名稱:node-microframework,代碼行數:10,代碼來源:application.ts

示例10: constructor

    /**
     * Constructor.
     *
     * @class Server
     * @constructor
     */
    constructor() {
        // create expressjs application
        this.app = express();
        this.app.use(bodyParser.json());

        this.app.use(cors());

        // configure application
        this.config();
    }
開發者ID:fabiopavesi,項目名稱:EDI-NG_client,代碼行數:16,代碼來源:server.ts


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