diff --git a/lib/app/server.js b/lib/app/server.js index c4527ea8da..2bcbd2093e 100644 --- a/lib/app/server.js +++ b/lib/app/server.js @@ -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() } diff --git a/lib/app/utils.js b/lib/app/utils.js index 58aabee886..d65a42a1a4 100644 --- a/lib/app/utils.js +++ b/lib/app/utils.js @@ -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