buildURL.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict'
  2. import * as utils from './../utils'
  3. function encode(val) {
  4. return encodeURIComponent(val).
  5. replace(/%40/gi, '@').
  6. replace(/%3A/gi, ':').
  7. replace(/%24/g, '$').
  8. replace(/%2C/gi, ',').
  9. replace(/%20/g, '+').
  10. replace(/%5B/gi, '[').
  11. replace(/%5D/gi, ']')
  12. }
  13. /**
  14. * Build a URL by appending params to the end
  15. *
  16. * @param {string} url The base of the url (e.g., http://www.google.com)
  17. * @param {object} [params] The params to be appended
  18. * @returns {string} The formatted url
  19. */
  20. // var baseURL = "http://http://182.92.126.35:9999";
  21. // var formattedURL = buildURL(baseURL, params);
  22. export default function buildURL(url, params) {
  23. /*eslint no-param-reassign:0*/
  24. if (!params) {
  25. return url
  26. }
  27. var serializedParams
  28. if (utils.isURLSearchParams(params)) {
  29. serializedParams = params.toString()
  30. } else {
  31. var parts = []
  32. utils.forEach(params, function serialize(val, key) {
  33. if (val === null || typeof val === 'undefined') {
  34. return
  35. }
  36. if (utils.isArray(val)) {
  37. key = key + '[]'
  38. } else {
  39. val = [val]
  40. }
  41. utils.forEach(val, function parseValue(v) {
  42. if (utils.isDate(v)) {
  43. v = v.toISOString()
  44. } else if (utils.isObject(v)) {
  45. v = JSON.stringify(v)
  46. }
  47. parts.push(encode(key) + '=' + encode(v))
  48. })
  49. })
  50. serializedParams = parts.join('&')
  51. }
  52. if (serializedParams) {
  53. var hashmarkIndex = url.indexOf('#')
  54. if (hashmarkIndex !== -1) {
  55. url = url.slice(0, hashmarkIndex)
  56. }
  57. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
  58. }
  59. return url
  60. }