Пример #1
0
            Object.keys(proxySettings).forEach(function eachProxyRoute(proxyRoute) {
                const host = proxySettings[proxyRoute];
                logger.meta(`Proxy: ${proxyRoute} -> ${host}`);

                /* istanbul ignore next */
                app.use(proxy({
                    host,
                    map: (hostPath) => hostPath.replace(proxyRoute, ""),
                    match: proxyRoute
                }));
            });
Пример #2
0
module.exports = function(router, app, staticDir) {
    // mock api
    router.get('/api/list', function*() {
        var query = this.query || {};
        var offset = query.offset || 0;
        var limit = query.limit || 10;
        var diff = limit - list.length;

        if(diff <= 0) {
            this.body = {code: 0, data: list.slice(0, limit)};
        } else {
            var arr = list.slice(0, list.length);
            var i = 0;

            while(diff--) arr.push(arr[i++]);

            this.body = {code: 0, data: arr};
        }
    });

    // proxy api
    router.get('/api/foo/bar', proxy({url: 'http://foo.bar.com'}));

    render(app, {
        root: __dirname,
        layout: false,
        viewExt: 'html',
        cache: false,
        debug: true
    });

    router.get('/', function*() {
        var pages = fs.readdirSync(staticDir);

        pages = pages.filter(function(page) {
            return /\.html$/.test(page);
        });

        yield this.render('home', {pages: pages || []});
    });
};
Пример #3
0
export default function(params) {

  const app = koa();

  // static assets (built by webpack)
  if (DEV) {
    const proxy = require('koa-proxy');

    // proxy to the webpack dev server when in dev mode
    app.use(proxy({
      host: `http://${WDS_HOST}:${WDS_PORT}`,
      match: /^\/assets\//,
    }));
  } else {
    app.use(mount('/assets', StaticHandler(path.join(REPO_ROOT, 'build'))));
  }

  // React handler
  app.use(Handler(params));

  console.log('LISTENING ON PORT', PORT);
  app.listen(PORT);
}
Пример #4
0
    if(m.some(function(i){return useragent.match(i);})){
      console.log('m')
      yield send(this, path.join(this.path,'dist/client/index_m.html'));
    }else{
      console.log('pc')
      yield send(this, path.join(this.path,'dist/client/index.html'));
    }
  } else {
    yield next
  }
})

app.use(staticServe(config.staticPath));

app.use(proxy({
  host: 'http://www.uat.chunbo.com',
  match:/^\/product|login/
}))

app.use(proxy({
  host: 'http://cms.chunbo.com',
  match:/^\/CmsHome/
}));

app.use(proxy({
  host: 'http://api.chunbo.com',
  match:/^\/Category/
}));

app.use(bodyParser());

app.use(router.routes());
Пример #5
0
var koa = require('koa');
var router = require('koa-router')();// koa路由
var proxy = require('koa-proxy');// 代理 可以重定向访问base路径,即访问本地时可以像访问重定向url一样
var staticServer = require('koa-static');
var path = require('path');

var app = koa();

var apiProxy = proxy({host: 'http://tstest.zlapi.com'});

router.get('/helloworld', function *(next){
    this.body = 'hello world';
})
.get('/users', function *(next){
    this.body = '<a href="http://www.baidu.com">百度</a>';
})
.get('/toy/*',apiProxy);

// 与普通的 function 不同,generator functions 以 function* 声明。以这种关键词声明的函数支持 yield

app.use(router.routes());

app.use(staticServer(path.join(__dirname,'')));

app.listen(8787, '0.0.0.0', function () {
	console.log('app listen success');
});

// 上面基本等价于
// var http = require('http');
// http.createServer(app.callback()).listen(8888);
export default async () => {
  const app = new Koa()
  var clientInfo

  // Enable koa-proxy if it has been enabled in the config.
  if (config.proxy && config.proxy.enabled) {
    app.use(convert(proxy(config.proxy.options)))
  }

  if (!config.universal || !config.universal.enabled) {
    // This rewrites all routes requests to the root /index.html file
    // (ignoring file requests).
    debug('Enable HistoryApiFallback middleware.')
    app.use(convert(historyApiFallback({
      verbose: false
    })))
  }

  // ------------------------------------
  // Apply Webpack HMR Middleware
  // ------------------------------------
  if (config.env === 'development') {
    const compiler = webpack(webpackConfigClient)

    // Enable webpack-dev and webpack-hot middleware
    const { publicPath } = webpackConfigClient.output

    // Catch the hash of the build in order to use it in the universal middleware
    config.universal && config.universal.enabled && compiler.plugin('done', stats => {
      // Create client info from the fresh build
      clientInfo = {
        assetsByChunkName: {
          app: `app.${stats.hash}.js`,
          vendor: `vendor.${stats.hash}.js`
        }
      }
    })

    app.use(webpackDevMiddleware(compiler, publicPath))
    app.use(webpackHMRMiddleware(compiler))

    // Serve static assets from ~/src/static since Webpack is unaware of
    // these files. This middleware doesn't need to be enabled outside
    // of development since this directory will be copied into ~/dist
    // when the application is compiled.
    app.use(serve(path.join(config.paths.src, 'static')))
  } else {
    if (config.universal.enabled) {
      // Get assets from client_info.json
      debug('Read client info.')
      fs.readJSON(path.join(config.paths.dist, config.universal.client_info), (err, data) => {
        if (err) {
          clientInfo = {}
          debug('Failed to read client_data!')
          return
        }
        clientInfo = data
      })
    } else {
      debug(
        'Server is being run outside of live development mode, meaning it will ' +
        'only serve the compiled application bundle in ~/dist. Generally you ' +
        'do not need an application server for this and can instead use a web ' +
        'server such as nginx to serve your static files. See the "deployment" ' +
        'section in the README for more information on deployment strategies.'
      )
    }

    // Serving ~/dist by default. Ideally these files should be served by
    // the web server and not the app server when universal is turned off,
    // but this helps to demo the server in production.
    app.use(serve(config.paths.public))
  }

  if (config.universal && config.universal.enabled) {
    try {
      let um = await universalMiddleware()
      app.use(um.default(() => clientInfo))
    } catch (err) {
      debug('ERROR! Aborting server start due to error: ', err)
      throw err
    }
  }

  return Promise.resolve(app)
}
Пример #7
0
// template ejs
app.use(views(templatePath, { extension: 'ejs' }))

app.use(async function(ctx, next){
  console.log("中间件1------>start")
  var start = new Date;
  await next();
  var ms = new Date - start;
  console.log("中间件1------>end,服务器响应耗时:" + ms + 'ms');
});

app.on('error', function(err){
  console.log("server error: ---->from index.js")
  console.log(err)
});


import renderRouter from './routers/server';
app.use(proxy({
  host:  'http://www.sojson.com',
  match: /^\/api\//,
  map: function(path) { return path.replace('/api/', '/'); }
}));
app.use(renderRouter);


var port = 2018;
app.listen(port);
console.log("---->服务器启动完毕")
console.log("---->请访问: http://localhost:" + port)
Пример #8
0
var compiler = webpack(webpackConfig);

app.use(koaStatic(serverConfig.static, {}));

/*app.use(webpackDevMiddleware(compiler, {
	noInfo: true
}));

app.use(function *(next) {
    yield webpackHotMiddleware(compiler).bind(null, this.req, this.res);
    yield next;
});*/

app.use(proxy({
	host: serverConfig.proxy
}));

app.use(function *(next) {
	var url = this.url;
	if (url === '/') {
		var file = path.join(__dirname, 'src', 'index.html');
		var stat = fs.statSync(file);
		this.response.status = 200;
		this.response.length = stat.size;
		this.response.type = path.extname(file);
		this.response.body = fs.createReadStream(file)
	}
	yield next;
});
Пример #9
0
import 'babel-polyfill';
require('isomorphic-fetch');
import koa from 'koa';
import koaProxy from 'koa-proxy';
import Transmit from 'react-transmit';
import Root from 'Components/Root';

try {
  const app = koa();
  const hostname = process.env.HOSTNAME || 'localhost';
  const port = process.env.PORT || 3000;
  const webserver = `http://${hostname}:${port}`;
  const neosBackendUrl = 'http://dev.neos-react.loc';

  app.use(koaProxy({
    host: neosBackendUrl,
    match: /^\/query/i,
  }));

  app.use(function *(next) {
    yield ((callback) => {
      Transmit.renderToString(Root).then(({reactString, reactData}) => {
        const template = (
          `<!doctype html>
          <html lang='en-us'>
            <head>
              <meta charset='utf-8' />
              <title>Neos React Rendering</title>
            </head>
            <body>
              <div id='react-root'>${reactString}</div>
            </body>
Пример #10
0
import ReactDOM from "react-dom/server";
import {RoutingContext, match} from "react-router";
import {createLocation} from "history";
import Transmit from "react-transmit";

import routes from "views/routes";

const app      = koa();
const hostname = process.env.HOSTNAME || "localhost";
const port     = process.env.PORT || 8000;

app.use(serve("static", {defer: true}));

app.use(proxy({
	host: "https://api.github.com",
	match: /^\/api\/github\//i,
	map: (path) => path.replace(/^\/api\/github\//i, "/")
}));

app.use(function *(next) {
	const location = createLocation(this.path);
	const webserver = process.env.NODE_ENV === "production" ? "" : "//" + hostname + ":8080";

	yield ((callback) => {
		match({routes, location}, (error, redirectLocation, renderProps) => {
			if (redirectLocation) {
				this.redirect(redirectLocation.pathname + redirectLocation.search, "/");
				return;
			}

			if (error || !renderProps) {
Пример #11
0
try {
  const Schema = require('../data/schema');

  graphQLServer.use(graphqlHTTP({
    schema: Schema,
    pretty: true,
  }));

  graphQLServer.listen(GRAPHQL_PORT, () => {
    console.log(
      green(`GraphQL Server running at http://localhost:${GRAPHQL_PORT}`)
    );
  });

  app.use(mount('/graphql', proxy({
    host: 'http://localhost:8080',
  })));
} catch (ex) {
  console.error(red('ERROR: Cannot find schema.json.'));
}

if (ENV === 'development') {
  app.use(mount('/build', proxy({
    host: `http://localhost:${WEBPACK_PORT}`,
  })));
}

app.use(compress());
app.use(bodyparser());
app.use(statics(path.join(__dirname, '..', 'public')));
app.use(function* render() {
Пример #12
0
//     cache: process.env !== 'development'
// }));

// 压缩服务
appForHtml.use(compress({
    flush: require('zlib').Z_SYNC_FLUSH
}));

// 响应头
appForHtml.use(function* (next) {
    yield next;
    this.set('Content-Type', 'html');
});

// api代理
appForHtml.use(proxy(proxyConfig));

// 路由
appForHtml.use(router);

// 开启监听
appForHtml.listen(ports.page, function () {
    console.log('pages server listen: ' + ports.page);
});

// ---------------------------------------------------------------------------- 静态资源服务
// 日志
appForStatic.use(logger());

// 资源跨域
appForStatic.use(function* (next) {
Пример #13
0
  // Exchange token
  if (this.method === 'POST') {
    // Registration
    if (this.path === '/account' && this.status === 201) {
      yield exchangeCredentials.call(this, requestToken);
    }

    // Login
    if (this.path === '/login' && this.status === 200) {
      yield exchangeCredentials.call(this, requestToken);
    }
  }
}));

server.use(mount('/api', proxy({
  host: process.env.FRONTEND_API_URI || 'http://localhost:5000'
})));

// Register routes
log('registering routes');
const routers = [
  require('./api/root')
];

routers.forEach(function(router) {
  log(router.opts.prefix);
  server.use(router.routes());
  server.use(router.allowedMethods());
});

// Start listening
Пример #14
0
import config from '../config';
import webpackProxyMiddleware from './middleware/webpack-proxy';
import webpackDevMiddleware from './middleware/webpack-dev';
import webpackHMRMiddleware from './middleware/webpack-hmr';

const debug = _debug('app:server');
const paths = config.utils_paths;
const app = new Koa();

// ------------------------------------
// Apply proxy for API mocks
// ------------------------------------
if (config.env === 'development') {
  app.use(convert(proxy({
    host: 'http://localhost:8000',
    match: /^\/api\//,
    map: drop(4)
  })));
}

// This rewrites all routes requests to the root /index.html file
// (ignoring file requests). If you want to implement isomorphic
// rendering, you'll want to remove this middleware.
app.use(convert(historyApiFallback({
  verbose: false
})));

// ------------------------------------
// Apply Webpack HMR Middleware
// ------------------------------------
if (config.env === 'development') {
Пример #15
0
		}
	});
};

try {
	const app = koa();
	const hostname = process.env.HOSTNAME || "localhost";
	const port = process.env.PORT || 4000;

	let routes = routesContainer;

	app.use(koaStatic("static"));

	app.use(koaProxy({
		host: githubApi.url,
		match: /^\/api\/github\//i,
		map: (path) => path.replace(/^\/api\/github\//i, "/")
	}));

	app.use(function *(next) {
		yield ((callback) => {
			const webserver = __PRODUCTION__ ? "" : `//${this.hostname}:${this.port}`;
			const location = this.path;

			match({routes, location}, (error, redirectLocation, renderProps) => {
				if (redirectLocation) {
					this.redirect(redirectLocation.pathname + redirectLocation.search, "/");
					return;
				}

				if (error || !renderProps) {
Пример #16
0
import _debug from 'debug'
import config from '../config'
import webpackDevMiddleware from './middleware/webpack-dev'
import webpackHMRMiddleware from './middleware/webpack-hmr'

import vimeoApiMiddleware from './middleware/vimeo'

const debug = _debug('app:server')
const paths = config.utils_paths
const app = new Koa()

app.use(vimeoApiMiddleware)

// Enable koa-proxy if it has been enabled in the config.
if (config.proxy && config.proxy.enabled) {
  app.use(convert(proxy(config.proxy.options)))
}

// This rewrites all routes requests to the root /index.html file
// (ignoring file requests). If you want to implement isomorphic
// rendering, you'll want to remove this middleware.
app.use(convert(historyApiFallback({
  verbose: false
})))

// ------------------------------------
// Apply Webpack HMR Middleware
// ------------------------------------
if (config.env === 'development') {
  const compiler = webpack(webpackConfig)
Пример #17
0
// allow both legacy and modern middleware
// https://www.npmjs.com/package/koa-convert
const use = app.use;
app.use = x => use.call(app, convert(x));

app
  .use(bodyParser());

/**
 * Loads the development specific functions
 * @param  {Boolean} __DEV__ Global variable for development environment
 * @return {InitDev}        The initializer class for development
 */
if (!process.env === 'production') {
  app.use(convert(proxy({
    host: `http://${SERVER_HOST}:${WEBPACK_DEV_SERVER_PORT}`,
    match: /^\/build\//
  })));
}

// App logging
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const end = new Date();
  logger.verbose(`${ctx.method} ${ctx.status} ${ctx.url} => ${end - start}ms`);
});

/**
 * Middlewares set to be available on context.
 * @method use
 */