How to use cors - 10 common examples

To help you get started, we’ve selected a few cors examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jimmyleray / Emendare / old-server / src / index.ts View on Github external
// Chalk for colored logs
import chalk from 'chalk'

// Initial server log
console.log(chalk.green('> Emendare Server launch\n'))

// Global configuration
import config from './config'

// Express Html Application
import express from 'express'
const app = express()

// CORS definition
import cors from 'cors'
app.use(cors({ origin: config.clientUrl }))

// Server basics imports
import { Server } from 'http'
import socketIO from 'socket.io'
import * as routes from './routes'
import * as tasks from './tasks'

// MongoDB connection
import { Database } from './services'
new Database()
  .connect()
  .then(() => {
    // Update database
    tasks.databaseMigrations()

    // Add Socket.io to Express server
github RD17 / ambar / WebApi / src / index.js View on Github external
import slao from 'slao'
import { ErrorHandlerService, EsProxy, StorageService } from './services'

const createLogRecord = (type, message) => ({
	type: type,
	source_id: 'webapi',
	message: message
})

let app = express()

app.server = http.createServer(app)

app.use(slao.init({ appName: 'ambar-webapi' }))

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

app.use(bodyParser.json({
	limit: config.bodyLimit
}))

// connect to storage
StorageService.initializeStorage()
	.then((storage) => {
		app.use('/api', api({ config, storage }))
		app.use(ErrorHandlerService(storage.elasticSearch))
		app.server.listen(process.env.PORT || config.localPort)

		//eslint-disable-next-line no-console
github danielstern / express-react-fullstack / src / server / server.js View on Github external
import bodyParser from 'body-parser';

import './initialize-db';
import { authenticationRoute } from './authenticate'

import { connectDB } from './connect-db'
import { addNewTask, updateTask } from './communicate-db';


let port = process.env.PORT || 7777;
let app = express();



app.use(
    cors(),
    bodyParser.urlencoded({extended:true}),
    bodyParser.json()
);
app.listen(port,console.info("Server running, listening on port ", port));

authenticationRoute(app);

if (process.env.NODE_ENV == `production`) {
    app.use(express.static(path.resolve(__dirname,'../../dist')));
    app.get('/*',(req,res)=>{
        res.sendFile(path.resolve('index.html'));
    });
}

app.post('/task/new',async (req,res)=>{
    // let task = req.body.task;
github bahdcasts / more-recipes / server / index.js View on Github external
import bodyParser from 'body-parser';
import swaggerUi from 'swagger-ui-express';

import routes from './routes';
import db from './database/models';
import middleware from './middleware';
import swaggerDoc from '../api-docs/swagger.json'

//  Configure environment variables

const app = new express();


//  Enable CORS for the express server
app.use(cors());
app.options('*', cors());

// Enable HTTP REQUEST logging
app.use(morgan('combined'));

const port = process.env.PORT || 5678;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'));
app.set('appPath', 'public');
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => res.render('index'));

app.use(middleware.api);
github timzprof / book-a-meal / api / index.js View on Github external
import Caterer from './models/caterer';
import Meal from './models/meals';
import Menu from './models/menu';
import Order from './models/orders';
import OrderItem from './models/orderItem';
import swaggerDocument from './swagger.json';

config();

const app = express();

const PORT = process.env.PORT || 4000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(fileUpload());
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/api/v1', Routes);

User.hasMany(Order, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(OrderItem, { constraints: true, onDelete: 'CASCADE' });
Order.belongsTo(Caterer, { constraints: true, onDelete: 'CASCADE' });
Meal.belongsTo(Caterer, { constraints: true, onDelete: 'CASCADE' });
Menu.belongsTo(Caterer, { constraints: true, onDelete: 'CASCADE' });
OrderItem.belongsTo(Meal, { constraints: true, onDelete: 'CASCADE' });

sequelize
  .sync()
  .then(() => {
    console.log('DB Connection has been established');
    app.listen(PORT, null, null, () => {
github OriginProtocol / origin / origin-linking / src / index.js View on Github external
import '@babel/polyfill'
import express from 'express'
import cookieParser from 'cookie-parser'
import expressWs from 'express-ws'
import useragent from 'express-useragent'
import cors from 'cors'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import 'express-async-errors'

const app = express()
expressWs(app)
app.use(cookieParser())
app.use(morgan('combined'))
app.use(useragent.express())
app.use(cors({ origin: true, credentials: true }))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

import linkerRoutes from './linker-routes'

const port = 3008

app.use('/api/wallet-linker', linkerRoutes)

app.listen(port, () => console.log(`Linking server listening on port ${port}!`))

export default app
github EOSIO / eosio-project-demux-example / backend / src / index.js View on Github external
import 'dotenv/config'
import express from 'express'
import cors from 'cors'
import demux from './services/demux'
import posts from './routes/posts'
import io from './utils/io'

let app = express()

app.use(cors())

app.use('/posts', posts())

const server = app.listen(process.env.PORT, () => console.info(`Example app listening on port ${process.env.PORT}!`))

io.connect(server)

demux.watch()
github christian-bromann / devtools-backend / lib / index.js View on Github external
this.preflightCheck()

        /**
         * initialise external middleware
         */
        this.app.use(bodyParser.urlencoded({ extended: false }))
        this.app.use(bodyParser.json())
        this.app.set('view engine', 'ejs')
        this.app.set('views', VIEWS_PATH)
        this.app.engine('html', ejs.renderFile)
        this.app.use(cookieParser())

        /**
         * enable cors
         */
        this.app.use(cors())
        this.app.disable('etag')

        /**
         * paths
         */
        this.app.get('/', this.filterRequests(::this.inspectablePages))
        this.app.get('/json', this.filterRequests(::this.json))
        this.app.post('/register', this.filterRequests(::this.register))
        this.app.use('/devtools', this.filterRequests(express.static(DEVTOOLS_PATH)))
        this.app.use('/scripts', this.filterRequests(express.static(SCRIPT_PATH)))

        /**
         * initialise socket server
         */
        this.server = this.app.listen(this.port,
            () => this.log.info(`Started devtools-backend server on ${this.host}:${this.port}`))
github labzero / lunch / src / api / main / teams.js View on Github external
cors(corsOptionsDelegate),
      loggedIn,
      getTeam,
      checkTeamRole('owner'),
      async (req, res, next) => {
        try {
          await req.team.destroy();
          return res.status(204).send();
        } catch (err) {
          return next(err);
        }
      }
    )
    .patch(
      '/:id',
      cors(corsOptionsDelegate),
      loggedIn,
      getTeam,
      checkTeamRole(),
      async (req, res, next) => {
        const message409 = 'Could not update team. Its new URL might already exist.';
        let fieldCount = 0;

        const allowedFields = [{ name: 'default_zoom', type: 'number' }];
        if (hasRole(req.user, req.team, 'owner')) {
          allowedFields.push({
            name: 'address',
            type: 'string'
          }, {
            name: 'lat',
            type: 'number'
          }, {

cors

Node.js CORS middleware

MIT
Latest version published 5 years ago

Package Health Score

84 / 100
Full package analysis

Popular cors functions