PageRenderTime 2305ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/core/dev-utils/prepareProxy.js

https://github.com/egoist/poi
JavaScript | 139 lines | 99 code | 8 blank | 32 comment | 10 complexity | 54462f609494267479f76de2f0eb5701 MD5 | raw file
  1. const fs = require('fs')
  2. const path = require('path')
  3. const url = require('url')
  4. const address = require('address')
  5. const colors = require('./colors')
  6. module.exports = function(proxy, appPublicFolder, debug) {
  7. // `proxy` lets you specify alternate servers for specific requests.
  8. if (!/^https?:\/\//.test(proxy)) {
  9. throw new Error(
  10. `When specified \`proxy\` as a string, it must start with http:// or https://`
  11. )
  12. }
  13. // If proxy is specified, let it handle any request except for files in the public folder.
  14. function mayProxy(pathname) {
  15. const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1))
  16. return !fs.existsSync(maybePublicPath)
  17. }
  18. let target
  19. if (process.platform === 'win32') {
  20. target = resolveLoopback(proxy)
  21. } else {
  22. target = proxy
  23. }
  24. return [
  25. {
  26. target,
  27. logLevel: debug ? 'debug' : 'silent',
  28. // For single page apps, we generally want to fallback to /index.html.
  29. // However we also want to respect `proxy` for API calls.
  30. // So if `proxy` is specified as a string, we need to decide which fallback to use.
  31. // We use a heuristic: We want to proxy all the requests that are not meant
  32. // for static assets and as all the requests for static assets will be using
  33. // `GET` method, we can proxy all non-`GET` requests.
  34. // For `GET` requests, if request `accept`s text/html, we pick /index.html.
  35. // Modern browsers include text/html into `accept` header when navigating.
  36. // However API calls like `fetch()` won’t generally accept text/html.
  37. // If this heuristic doesn’t work well for you, use `src/setupProxy.js`.
  38. context(pathname, req) {
  39. // Explict context
  40. if (pathname.startsWith('/api/')) {
  41. return true
  42. }
  43. return (
  44. req.method !== 'GET' ||
  45. (mayProxy(pathname) &&
  46. req.headers.accept &&
  47. req.headers.accept.indexOf('text/html') === -1)
  48. )
  49. },
  50. onProxyReq: proxyReq => {
  51. // Browsers may send Origin headers even with same-origin
  52. // requests. To prevent CORS issues, we have to change
  53. // the Origin to match the target URL.
  54. if (proxyReq.getHeader('origin')) {
  55. proxyReq.setHeader('origin', target)
  56. }
  57. },
  58. onError: onProxyError(target),
  59. secure: false,
  60. changeOrigin: true,
  61. ws: true,
  62. xfwd: true
  63. }
  64. ]
  65. }
  66. // We need to provide a custom onError function for httpProxyMiddleware.
  67. // It allows us to log custom error messages on the console.
  68. function onProxyError(proxy) {
  69. return (err, req, res) => {
  70. const host = req.headers && req.headers.host
  71. console.log(
  72. colors.red('Proxy error:') +
  73. ' Could not proxy request ' +
  74. colors.cyan(req.url) +
  75. ' from ' +
  76. colors.cyan(host) +
  77. ' to ' +
  78. colors.cyan(proxy) +
  79. '.'
  80. )
  81. console.log(
  82. 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
  83. colors.cyan(err.code) +
  84. ').'
  85. )
  86. console.log()
  87. // And immediately send the proper error response to the client.
  88. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
  89. if (res.writeHead && !res.headersSent) {
  90. res.writeHead(500)
  91. }
  92. res.end(
  93. 'Proxy error: Could not proxy request ' +
  94. req.url +
  95. ' from ' +
  96. host +
  97. ' to ' +
  98. proxy +
  99. ' (' +
  100. err.code +
  101. ').'
  102. )
  103. }
  104. }
  105. function resolveLoopback(proxy) {
  106. const o = url.parse(proxy)
  107. o.host = undefined
  108. if (o.hostname !== 'localhost') {
  109. return proxy
  110. }
  111. // Unfortunately, many languages (unlike node) do not yet support IPv6.
  112. // This means even though localhost resolves to ::1, the application
  113. // must fall back to IPv4 (on 127.0.0.1).
  114. // We can re-enable this in a few years.
  115. /* try {
  116. o.hostname = address.ipv6() ? '::1' : '127.0.0.1';
  117. } catch (_ignored) {
  118. o.hostname = '127.0.0.1';
  119. } */
  120. try {
  121. // Check if we're on a network; if we are, chances are we can resolve
  122. // localhost. Otherwise, we can just be safe and assume localhost is
  123. // IPv4 for maximum compatibility.
  124. if (!address.ip()) {
  125. o.hostname = '127.0.0.1'
  126. }
  127. } catch (_) {
  128. o.hostname = '127.0.0.1'
  129. }
  130. return url.format(o)
  131. }