prepareProxy.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file at
  6. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  7. */
  8. const fs = require('fs')
  9. const url = require('url')
  10. const path = require('path')
  11. const chalk = require('chalk')
  12. const address = require('address')
  13. const defaultConfig = {
  14. logLevel: 'silent',
  15. secure: false,
  16. changeOrigin: true,
  17. ws: true,
  18. xfwd: true
  19. }
  20. module.exports = function prepareProxy (proxy, appPublicFolder) {
  21. // `proxy` lets you specify alternate servers for specific requests.
  22. // It can either be a string or an object conforming to the Webpack dev server proxy configuration
  23. // https://webpack.github.io/docs/webpack-dev-server.html
  24. if (!proxy) {
  25. return undefined
  26. }
  27. if (Array.isArray(proxy) || (typeof proxy !== 'object' && typeof proxy !== 'string')) {
  28. console.log(
  29. chalk.red(
  30. 'When specified, "proxy" in package.json must be a string or an object.'
  31. )
  32. )
  33. console.log(
  34. chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')
  35. )
  36. console.log(
  37. chalk.red(
  38. 'Either remove "proxy" from package.json, or make it an object.'
  39. )
  40. )
  41. process.exit(1)
  42. }
  43. // Otherwise, if proxy is specified, we will let it handle any request except for files in the public folder.
  44. function mayProxy (pathname) {
  45. const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1))
  46. return !fs.existsSync(maybePublicPath)
  47. }
  48. function createProxyEntry (target, usersOnProxyReq, context) {
  49. // #2478
  50. // There're a little-known use case that the `target` field is an object rather than a string
  51. // https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/https.md
  52. if (typeof target === 'string' && process.platform === 'win32') {
  53. target = resolveLoopback(target)
  54. }
  55. return {
  56. target,
  57. context (pathname, req) {
  58. // is a static asset
  59. if (!mayProxy(pathname)) {
  60. return false
  61. }
  62. if (context) {
  63. // Explicit context, e.g. /api
  64. return pathname.match(context)
  65. } else {
  66. // not a static request
  67. if (req.method !== 'GET') {
  68. return true
  69. }
  70. // Heuristics: if request `accept`s text/html, we pick /index.html.
  71. // Modern browsers include text/html into `accept` header when navigating.
  72. // However API calls like `fetch()` won’t generally accept text/html.
  73. // If this heuristic doesn’t work well for you, use a custom `proxy` object.
  74. return (
  75. req.headers.accept &&
  76. req.headers.accept.indexOf('text/html') === -1
  77. )
  78. }
  79. },
  80. onProxyReq (proxyReq, req, res) {
  81. if (usersOnProxyReq) {
  82. usersOnProxyReq(proxyReq, req, res)
  83. }
  84. // Browsers may send Origin headers even with same-origin
  85. // requests. To prevent CORS issues, we have to change
  86. // the Origin to match the target URL.
  87. if (!proxyReq.agent && proxyReq.getHeader('origin')) {
  88. proxyReq.setHeader('origin', target)
  89. }
  90. },
  91. onError: onProxyError(target)
  92. }
  93. }
  94. // Support proxy as a string for those who are using the simple proxy option
  95. if (typeof proxy === 'string') {
  96. if (!/^http(s)?:\/\//.test(proxy)) {
  97. console.log(
  98. chalk.red(
  99. 'When "proxy" is specified in package.json it must start with either http:// or https://'
  100. )
  101. )
  102. process.exit(1)
  103. }
  104. return [
  105. Object.assign({}, defaultConfig, createProxyEntry(proxy))
  106. ]
  107. }
  108. // Otherwise, proxy is an object so create an array of proxies to pass to webpackDevServer
  109. return Object.keys(proxy).map(context => {
  110. const config = proxy[context]
  111. if (!config.hasOwnProperty('target')) {
  112. console.log(
  113. chalk.red(
  114. 'When `proxy` in package.json is an object, each `context` object must have a ' +
  115. '`target` property specified as a url string'
  116. )
  117. )
  118. process.exit(1)
  119. }
  120. const entry = createProxyEntry(config.target, config.onProxyReq, context)
  121. return Object.assign({}, defaultConfig, config, entry)
  122. })
  123. }
  124. function resolveLoopback (proxy) {
  125. const o = url.parse(proxy)
  126. o.host = undefined
  127. if (o.hostname !== 'localhost') {
  128. return proxy
  129. }
  130. // Unfortunately, many languages (unlike node) do not yet support IPv6.
  131. // This means even though localhost resolves to ::1, the application
  132. // must fall back to IPv4 (on 127.0.0.1).
  133. // We can re-enable this in a few years.
  134. /* try {
  135. o.hostname = address.ipv6() ? '::1' : '127.0.0.1';
  136. } catch (_ignored) {
  137. o.hostname = '127.0.0.1';
  138. }*/
  139. try {
  140. // Check if we're on a network; if we are, chances are we can resolve
  141. // localhost. Otherwise, we can just be safe and assume localhost is
  142. // IPv4 for maximum compatibility.
  143. if (!address.ip()) {
  144. o.hostname = '127.0.0.1'
  145. }
  146. } catch (_ignored) {
  147. o.hostname = '127.0.0.1'
  148. }
  149. return url.format(o)
  150. }
  151. // We need to provide a custom onError function for httpProxyMiddleware.
  152. // It allows us to log custom error messages on the console.
  153. function onProxyError (proxy) {
  154. return (err, req, res) => {
  155. const host = req.headers && req.headers.host
  156. console.log(
  157. chalk.red('Proxy error:') +
  158. ' Could not proxy request ' +
  159. chalk.cyan(req.url) +
  160. ' from ' +
  161. chalk.cyan(host) +
  162. ' to ' +
  163. chalk.cyan(proxy) +
  164. '.'
  165. )
  166. console.log(
  167. 'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
  168. chalk.cyan(err.code) +
  169. ').'
  170. )
  171. console.log()
  172. // And immediately send the proper error response to the client.
  173. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
  174. if (res.writeHead && !res.headersSent) {
  175. res.writeHead(500)
  176. }
  177. res.end(
  178. 'Proxy error: Could not proxy request ' +
  179. req.url +
  180. ' from ' +
  181. host +
  182. ' to ' +
  183. proxy +
  184. ' (' +
  185. err.code +
  186. ').'
  187. )
  188. }
  189. }