kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

TypeError: Expected "number" to be a string #139

Closed luongthanhlam closed 6 years ago

luongthanhlam commented 6 years ago

When I call url('user', { id: 11, slugs: 'abc' }), it throw an error

TypeError: Expected "number" to be a string
    at Object.toPath (/.../node_modules/path-to-regexp/index.js:188:13)
    at /.../node_modules/universal-router/src/generateUrls.js:78:39

Here are my routes.js:

 { name: 'user', path: ['/:id(\\d+)-:slugs/page-:number(\\d+)', '/:id(\\d+)-:slugs'] }
frenzzy commented 6 years ago

generateUrls uses the first path from array of paths which contains required :number(\\d+) parameter in your example. You must provide the missed param or swap the paths.

url('user', { id: 11, slugs: 'abc', number: 22 }) // add `number` param

/* OR */

path: ['/:id(\\d+)-:slugs', '/:id(\\d+)-:slugs/page-:number(\\d+)'] // swap paths
luongthanhlam commented 6 years ago

When I swap paths, only the first part work

url('user', { id: 11, slugs: 'abc', number: 22 }) //=>/11-abc
frenzzy commented 6 years ago

Which the path url() should generate?

luongthanhlam commented 6 years ago

Well, I fixed it by adding the missing param but I think generateUrls should uses all paths from array of paths, not only the first.

frenzzy commented 6 years ago

Could you provide an example what URL should be generated in your case then?

luongthanhlam commented 6 years ago

Oh yes, here is an example in my case:

url('user', { id: 11, slugs: 'abc' }) // => /11-abc
url('user', { id: 11, slugs: 'abc', number: 200 }) // => /11-abc/200
frenzzy commented 6 years ago

You can make the latest parameter optional:

const route = {
  name: 'user',
  path: '/:id(\\d+)-:slugs/:number?' // <== question mark
}

url('user', { id: 11, slugs: 'abc' }) // => /11-abc
url('user', { id: 11, slugs: 'abc', number: 200 }) // => /11-abc/200

Playground: http://jsfiddle.net/frenzzy/h3Lfz42q/ Read more: path-to-regexp parameters

luongthanhlam commented 6 years ago

Thank you, it works perfectly