mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-24 06:35:10 +00:00
Fix middleware on server-side
This commit is contained in:
parent
5d4f289911
commit
4b675e3357
@ -1,3 +1,4 @@
|
|||||||
export default function ({ store, route }) {
|
export default function ({ store, route, redirect }) {
|
||||||
store.commit('ADD_VISIT', route.path)
|
store.commit('ADD_VISIT', route.path)
|
||||||
|
if (route.fullPath === '/') return redirect('/foo')
|
||||||
}
|
}
|
||||||
|
@ -12,6 +12,7 @@
|
|||||||
<script>
|
<script>
|
||||||
export default {
|
export default {
|
||||||
asyncData ({ store, route, userAgent }) {
|
asyncData ({ store, route, userAgent }) {
|
||||||
|
console.log('Call async data', route.fullPath)
|
||||||
return {
|
return {
|
||||||
userAgent,
|
userAgent,
|
||||||
slugs: [
|
slugs: [
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
import Vue from 'vue'
|
import Vue from 'vue'
|
||||||
import middleware from './middleware'
|
import middleware from './middleware'
|
||||||
import { app, router<%= (store ? ', store' : '') %>, NuxtError } from './index'
|
import { app, router<%= (store ? ', store' : '') %>, NuxtError } from './index'
|
||||||
import { applyAsyncData, getMatchedComponents, getMatchedComponentsInstances, flatMapComponents, getContext, promiseSeries, promisify, getLocation, compile } from './utils'
|
import { applyAsyncData, getMatchedComponents, getMatchedComponentsInstances, flatMapComponents, getContext, middlewareSeries, promisify, getLocation, compile } from './utils'
|
||||||
const noopData = () => { return {} }
|
const noopData = () => { return {} }
|
||||||
const noopFetch = () => {}
|
const noopFetch = () => {}
|
||||||
let _lastPaths = []
|
let _lastPaths = []
|
||||||
@ -77,7 +77,7 @@ function callMiddleware (Components, context, layout) {
|
|||||||
return middleware[name]
|
return middleware[name]
|
||||||
})
|
})
|
||||||
if (unknownMiddleware) return
|
if (unknownMiddleware) return
|
||||||
return promiseSeries(midd, context)
|
return middlewareSeries(midd, context)
|
||||||
}
|
}
|
||||||
|
|
||||||
function render (to, from, next) {
|
function render (to, from, next) {
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const debug = require('debug')('nuxt:render')
|
|
||||||
debug.color = 4 // force blue color
|
|
||||||
import Vue from 'vue'
|
import Vue from 'vue'
|
||||||
|
|
||||||
import { stringify } from 'querystring'
|
import { stringify } from 'querystring'
|
||||||
import { omit } from 'lodash'
|
import { omit } from 'lodash'
|
||||||
import middleware from './middleware'
|
import middleware from './middleware'
|
||||||
import { app, router<%= (store ? ', store' : '') %>, NuxtError } from './index'
|
import { app, router<%= (store ? ', store' : '') %>, NuxtError } from './index'
|
||||||
import { applyAsyncData, getMatchedComponents, getContext, promiseSeries, promisify, urlJoin } from './utils'
|
import { applyAsyncData, sanitizeComponent, getMatchedComponents, getContext, middlewareSeries, promisify, urlJoin } from './utils'
|
||||||
|
const debug = require('debug')('nuxt:render')
|
||||||
|
debug.color = 4 // force blue color
|
||||||
|
|
||||||
const isDev = <%= isDev %>
|
const isDev = <%= isDev %>
|
||||||
const _app = new Vue(app)
|
const _app = new Vue(app)
|
||||||
@ -18,7 +17,7 @@ const _app = new Vue(app)
|
|||||||
// state of our application before actually rendering it.
|
// state of our application before actually rendering it.
|
||||||
// Since data fetching is async, this function is expected to
|
// Since data fetching is async, this function is expected to
|
||||||
// return a Promise that resolves to the app instance.
|
// return a Promise that resolves to the app instance.
|
||||||
export default context => {
|
export default async (context) => {
|
||||||
// Add store to the context
|
// Add store to the context
|
||||||
<%= (store ? 'context.store = store' : '') %>
|
<%= (store ? 'context.store = store' : '') %>
|
||||||
// Nuxt object
|
// Nuxt object
|
||||||
@ -47,37 +46,23 @@ export default context => {
|
|||||||
|
|
||||||
<%= (isDev ? 'const s = isDev && Date.now()' : '') %>
|
<%= (isDev ? 'const s = isDev && Date.now()' : '') %>
|
||||||
let ctx = null
|
let ctx = null
|
||||||
let componentsLoaded = false
|
|
||||||
let Components = []
|
let Components = []
|
||||||
let promises = getMatchedComponents(router.match(context.url)).map((Component) => {
|
let promises = getMatchedComponents(router.match(context.url)).map((Component) => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const _resolve = (Component) => {
|
const _resolve = (Component) => resolve(sanitizeComponent(Component))
|
||||||
if (!Component.options) {
|
|
||||||
Component = Vue.extend(Component) // fix issue #6
|
|
||||||
Component._Ctor = Component
|
|
||||||
} else {
|
|
||||||
Component._Ctor = Component
|
|
||||||
Component.extendOptions = Component.options
|
|
||||||
}
|
|
||||||
// For debugging purpose
|
|
||||||
if (!Component.options.name && Component.options.__file) {
|
|
||||||
Component.options.name = Component.options.__file
|
|
||||||
}
|
|
||||||
resolve(Component)
|
|
||||||
}
|
|
||||||
Component().then(_resolve).catch(reject)
|
Component().then(_resolve).catch(reject)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
return Promise.all(promises)
|
try {
|
||||||
.then((_Components) => {
|
Components = await Promise.all(promises)
|
||||||
componentsLoaded = true
|
} catch (err) {
|
||||||
Components = _Components
|
// Throw back error to renderRoute()
|
||||||
|
throw err
|
||||||
|
}
|
||||||
// set router's location
|
// set router's location
|
||||||
return new Promise((resolve) => {
|
await new Promise((resolve) => {
|
||||||
router.push(context.url, resolve)
|
router.push(context.url, resolve)
|
||||||
})
|
})
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
// Add route to the context
|
// Add route to the context
|
||||||
context.route = router.currentRoute
|
context.route = router.currentRoute
|
||||||
// Update context
|
// Update context
|
||||||
@ -89,21 +74,7 @@ export default context => {
|
|||||||
<% } else { %>
|
<% } else { %>
|
||||||
let promise = Promise.resolve()
|
let promise = Promise.resolve()
|
||||||
<% } %>
|
<% } %>
|
||||||
return promise
|
await promise
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
// Sanitize Components
|
|
||||||
Components = Components.map((Component) => {
|
|
||||||
let promises = []
|
|
||||||
if (!Component.options) {
|
|
||||||
Component = Vue.extend(Component)
|
|
||||||
Component._Ctor = Component
|
|
||||||
} else {
|
|
||||||
Component._Ctor = Component
|
|
||||||
Component.extendOptions = Component.options
|
|
||||||
}
|
|
||||||
return Component
|
|
||||||
})
|
|
||||||
// Call global middleware (nuxt.config.js)
|
// Call global middleware (nuxt.config.js)
|
||||||
let midd = <%= serialize(router.middleware, { isJSON: true }) %>
|
let midd = <%= serialize(router.middleware, { isJSON: true }) %>
|
||||||
midd = midd.map((name) => {
|
midd = midd.map((name) => {
|
||||||
@ -112,25 +83,20 @@ export default context => {
|
|||||||
}
|
}
|
||||||
return middleware[name]
|
return middleware[name]
|
||||||
})
|
})
|
||||||
if (context.nuxt.error) return
|
if (!context.nuxt.error) {
|
||||||
return promiseSeries(midd, ctx)
|
await middlewareSeries(midd, ctx)
|
||||||
})
|
}
|
||||||
.then(() => {
|
if (context.redirected) return _app
|
||||||
// Set layout
|
// Set layout
|
||||||
let layout = Components.length ? Components[0].options.layout : NuxtError.layout
|
let layout = Components.length ? Components[0].options.layout : NuxtError.layout
|
||||||
if (typeof layout === 'function') {
|
if (typeof layout === 'function') layout = layout(ctx)
|
||||||
layout = layout(ctx)
|
await _app.loadLayout(layout)
|
||||||
}
|
layout = _app.setLayout(layout)
|
||||||
return _app.loadLayout(layout).then(() => _app.setLayout(layout))
|
|
||||||
})
|
|
||||||
.then((layout) => {
|
|
||||||
// Set layout to __NUXT__
|
// Set layout to __NUXT__
|
||||||
context.nuxt.layout = _app.layoutName
|
context.nuxt.layout = _app.layoutName
|
||||||
// Call middleware (layout + pages)
|
// Call middleware (layout + pages)
|
||||||
let midd = []
|
midd = []
|
||||||
if (layout.middleware) {
|
if (layout.middleware) midd = midd.concat(layout.middleware)
|
||||||
midd = midd.concat(layout.middleware)
|
|
||||||
}
|
|
||||||
Components.forEach((Component) => {
|
Components.forEach((Component) => {
|
||||||
if (Component.options.middleware) {
|
if (Component.options.middleware) {
|
||||||
midd = midd.concat(Component.options.middleware)
|
midd = midd.concat(Component.options.middleware)
|
||||||
@ -142,10 +108,10 @@ export default context => {
|
|||||||
}
|
}
|
||||||
return middleware[name]
|
return middleware[name]
|
||||||
})
|
})
|
||||||
if (context.nuxt.error) return
|
if (!context.nuxt.error) {
|
||||||
return promiseSeries(midd, ctx)
|
await middlewareSeries(midd, ctx)
|
||||||
})
|
}
|
||||||
.then(() => {
|
if (context.redirected) return _app
|
||||||
// Call .validate()
|
// Call .validate()
|
||||||
let isValid = true
|
let isValid = true
|
||||||
Components.forEach((Component) => {
|
Components.forEach((Component) => {
|
||||||
@ -156,6 +122,7 @@ export default context => {
|
|||||||
query: context.route.query || {}<%= (store ? ', store: ctx.store' : '') %>
|
query: context.route.query || {}<%= (store ? ', store: ctx.store' : '') %>
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
// If .validate() returned false
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
// Don't server-render the page in generate mode
|
// Don't server-render the page in generate mode
|
||||||
if (context._generate) {
|
if (context._generate) {
|
||||||
@ -163,10 +130,9 @@ export default context => {
|
|||||||
}
|
}
|
||||||
// Call the 404 error by making the Components array empty
|
// Call the 404 error by making the Components array empty
|
||||||
Components = []
|
Components = []
|
||||||
return _app
|
|
||||||
}
|
}
|
||||||
// Call asyncData & fetch hooks on components matched by the route.
|
// Call asyncData & fetch hooks on components matched by the route.
|
||||||
return Promise.all(Components.map((Component) => {
|
let asyncDatas = await Promise.all(Components.map((Component) => {
|
||||||
let promises = []
|
let promises = []
|
||||||
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
|
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
|
||||||
let promise = promisify(Component.options.asyncData, ctx)
|
let promise = promisify(Component.options.asyncData, ctx)
|
||||||
@ -176,29 +142,25 @@ export default context => {
|
|||||||
return asyncDataResult
|
return asyncDataResult
|
||||||
})
|
})
|
||||||
promises.push(promise)
|
promises.push(promise)
|
||||||
} else {
|
} else promises.push(null)
|
||||||
promises.push(null)
|
// call fetch(context)
|
||||||
}
|
if (Component.options.fetch) promises.push(Component.options.fetch(ctx))
|
||||||
if (Component.options.fetch) {
|
else promises.push(null)
|
||||||
promises.push(Component.options.fetch(ctx))
|
|
||||||
} else {
|
|
||||||
promises.push(null)
|
|
||||||
}
|
|
||||||
return Promise.all(promises)
|
return Promise.all(promises)
|
||||||
}))
|
}))
|
||||||
})
|
// If no Components found, returns 404
|
||||||
.then((res) => {
|
|
||||||
if (!Components.length) {
|
if (!Components.length) {
|
||||||
context.nuxt.error = context.error({ statusCode: 404, message: 'This page could not be found.' })
|
context.nuxt.error = context.error({ statusCode: 404, message: 'This page could not be found.' })
|
||||||
<%= (store ? 'context.nuxt.state = store.state' : '') %>
|
|
||||||
return _app
|
|
||||||
}
|
}
|
||||||
<% if (isDev) { %>
|
<% if (isDev) { %>
|
||||||
debug('Data fetching ' + context.url + ': ' + (Date.now() - s) + 'ms')
|
if (asyncDatas.length) debug('Data fetching ' + context.url + ': ' + (Date.now() - s) + 'ms')
|
||||||
<% } %>
|
<% } %>
|
||||||
// datas are the first row of each
|
// datas are the first row of each
|
||||||
context.nuxt.data = res.map((r) => (r[0] || {}))
|
context.nuxt.data = asyncDatas.map((r) => (r[0] || {}))
|
||||||
|
// If an error occured in the execution
|
||||||
|
if (_app.$options._nuxt.err) {
|
||||||
context.nuxt.error = _app.$options._nuxt.err
|
context.nuxt.error = _app.$options._nuxt.err
|
||||||
|
}
|
||||||
<%= (store ? '// Add the state from the vuex store' : '') %>
|
<%= (store ? '// Add the state from the vuex store' : '') %>
|
||||||
<%= (store ? 'context.nuxt.state = store.state' : '') %>
|
<%= (store ? 'context.nuxt.state = store.state' : '') %>
|
||||||
// If no error, return main app
|
// If no error, return main app
|
||||||
@ -206,21 +168,15 @@ export default context => {
|
|||||||
return _app
|
return _app
|
||||||
}
|
}
|
||||||
// Load layout for error page
|
// Load layout for error page
|
||||||
let layout = (typeof NuxtError.layout === 'function' ? NuxtError.layout(ctx) : NuxtError.layout)
|
layout = (typeof NuxtError.layout === 'function' ? NuxtError.layout(ctx) : NuxtError.layout)
|
||||||
context.nuxt.layout = layout || ''
|
context.nuxt.layout = layout || ''
|
||||||
return _app.loadLayout(layout)
|
await _app.loadLayout(layout)
|
||||||
.then(() => _app.setLayout(layout))
|
_app.setLayout(layout)
|
||||||
.then(() => _app)
|
|
||||||
})
|
|
||||||
.catch(function (error) {
|
|
||||||
if (error instanceof Error || error.constructor.toString().indexOf('Error()') !== -1) {
|
|
||||||
return Promise.reject(error)
|
|
||||||
}
|
|
||||||
if (typeof error === 'string') {
|
|
||||||
error = { statusCode: 500, message: error }
|
|
||||||
}
|
|
||||||
context.nuxt.error = context.error(error)
|
|
||||||
<%= (store ? 'context.nuxt.state = store.state' : '') %>
|
|
||||||
return _app
|
return _app
|
||||||
})
|
// if (typeof error === 'string') {
|
||||||
|
// error = { statusCode: 500, message: error }
|
||||||
|
// }
|
||||||
|
// context.nuxt.error = context.error(error)
|
||||||
|
// <%= (store ? 'context.nuxt.state = store.state' : '') %>
|
||||||
|
// return _app
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
import Vue from 'vue'
|
||||||
import { app } from './index'
|
import { app } from './index'
|
||||||
|
|
||||||
const noopData = () => ({})
|
const noopData = () => ({})
|
||||||
@ -14,6 +15,21 @@ export function applyAsyncData (Component, asyncData = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function sanitizeComponent (Component) {
|
||||||
|
if (!Component.options) {
|
||||||
|
Component = Vue.extend(Component) // fix issue #6
|
||||||
|
Component._Ctor = Component
|
||||||
|
} else {
|
||||||
|
Component._Ctor = Component
|
||||||
|
Component.extendOptions = Component.options
|
||||||
|
}
|
||||||
|
// For debugging purpose
|
||||||
|
if (!Component.options.name && Component.options.__file) {
|
||||||
|
Component.options.name = Component.options.__file
|
||||||
|
}
|
||||||
|
return Component
|
||||||
|
}
|
||||||
|
|
||||||
export function getMatchedComponents (route) {
|
export function getMatchedComponents (route) {
|
||||||
return [].concat.apply([], route.matched.map(function (m) {
|
return [].concat.apply([], route.matched.map(function (m) {
|
||||||
return Object.keys(m.components).map(function (key) {
|
return Object.keys(m.components).map(function (key) {
|
||||||
@ -54,7 +70,7 @@ export function getContext (context) {
|
|||||||
ctx.query = ctx.route.query || {}
|
ctx.query = ctx.route.query || {}
|
||||||
ctx.redirect = function (status, path, query) {
|
ctx.redirect = function (status, path, query) {
|
||||||
if (!status) return
|
if (!status) return
|
||||||
ctx._redirected = true
|
ctx._redirected = true // Used in middleware
|
||||||
// if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' })
|
// if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' })
|
||||||
if (typeof status === 'string' && (typeof path === 'undefined' || typeof path === 'object')) {
|
if (typeof status === 'string' && (typeof path === 'undefined' || typeof path === 'object')) {
|
||||||
query = path || {}
|
query = path || {}
|
||||||
@ -82,13 +98,13 @@ export function getContext (context) {
|
|||||||
return ctx
|
return ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
export function promiseSeries (promises, context) {
|
export function middlewareSeries (promises, context) {
|
||||||
if (!promises.length || context._redirected) {
|
if (!promises.length || context._redirected) {
|
||||||
return Promise.resolve()
|
return Promise.resolve()
|
||||||
}
|
}
|
||||||
return promisify(promises[0], context)
|
return promisify(promises[0], context)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return promiseSeries(promises.slice(1), context)
|
return middlewareSeries(promises.slice(1), context)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user