Update the use of redirect(status, path, query)

This commit is contained in:
Sébastien Chopin 2016-11-11 01:35:05 +01:00
parent 78aabe480f
commit 4b0b83b782
2 changed files with 20 additions and 12 deletions

View File

@ -25,19 +25,17 @@ export default context => {
context.nuxt = { data: [], error: null<%= (store ? ', state: null' : '') %>, serverRendered: true }
// create context.next for simulate next() of beforeEach() when wanted to redirect
context.redirected = false
context.next = function (path) {
if (!path) return;
if (typeof path === 'string') path = { path }
path.query = stringify(path.query || {})
path.path = path.path + (path.query ? '?' + path.query : '')
path.path = urlJoin('<%= router.base %>', path.path)
context.next = function (opts) {
if (!context.res) {
context.redirected = path.path
context.redirected = opts
context.nuxt.serverRendered = false
return
}
context.res.writeHead(302, {
'Location': path.path
opts.query = stringify(opts.query)
opts.path = opts.path + (opts.query ? '?' + opts.query : '')
opts.path = urlJoin('<%= router.base %>', opts.path)
context.res.writeHead(opts.status, {
'Location': opts.path
})
context.res.end()
}

View File

@ -25,9 +25,19 @@ export function getContext (context) {
}
ctx.params = ctx.route.params || {}
ctx.query = ctx.route.query || {}
ctx.redirect = function (path) {
if (!path) return
context.next(path)
ctx.redirect = function (status, path, query) {
if (!status) return
// if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' })
if (typeof status === 'string' && (typeof path === 'undefined' || typeof path === 'object')) {
query = path || {}
path = status
status = 302
}
context.next({
path: path,
query: query,
status: status
})
}
if (context.req) ctx.req = context.req
if (context.res) ctx.res = context.res