Skip to content

Commit

Permalink
fix: router base not considered on redirecting in static mode (#1119)
Browse files Browse the repository at this point in the history
Resolves #1060
  • Loading branch information
rchl authored Mar 24, 2021
1 parent 67eccfe commit 75b7c6e
Show file tree
Hide file tree
Showing 6 changed files with 207 additions and 51 deletions.
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"scripts": {
"dev:basic": "nuxt -c ./test/fixture/basic/nuxt.config.js",
"dev:basic:generate": "nuxt generate -c ./test/fixture/basic/nuxt.config.js",
"start:dist": "jiti ./test/utils/http-server-internal.js --port 8080 -v dist",
"dev:basic:start": "nuxt start -c ./test/fixture/basic/nuxt.config.js",
"start:dist": "jiti ./test/utils/http-server-internal.js --port 8080 -v dist --base /nuxt/",
"coverage": "codecov",
"lint": "eslint --ext .js,.vue,.ts src test types && tsc",
"test": "yarn test:types && yarn test:unit && yarn test:e2e-ssr && yarn test:e2e-browser",
Expand Down Expand Up @@ -94,6 +95,7 @@
"is-https": "^3.0.0",
"js-cookie": "^2.2.1",
"klona": "^2.0.4",
"ufo": "^0.6.7",
"vue-i18n": "^8.23.0"
},
"devDependencies": {
Expand All @@ -107,7 +109,7 @@
"@release-it/conventional-changelog": "2.0.1",
"@types/argparse": "2.0.5",
"@types/cookie": "0.4.0",
"@types/finalhandler": "1.1.0",
"@types/express": "4.17.11",
"@types/jest": "26.0.20",
"@types/jest-dev-server": "4.2.0",
"@types/js-cookie": "2.2.6",
Expand All @@ -121,7 +123,7 @@
"codecov": "3.8.1",
"core-js": "3.9.1",
"eslint": "7.21.0",
"finalhandler": "1.1.2",
"express": "4.17.1",
"husky": "4.3.8",
"jest": "26.6.3",
"jest-dev-server": "4.4.0",
Expand Down
3 changes: 2 additions & 1 deletion src/templates/plugin.main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import { joinURL } from 'ufo'
import { nuxtI18nHead, nuxtI18nSeo } from './head-meta'
import { Constants, nuxtOptions, options } from './options'
import {
Expand Down Expand Up @@ -373,7 +374,7 @@ export default async (context) => {
if (process.client && process.static && nuxtOptions.isUniversalMode) {
const [_, redirectTo] = await onNavigate(context.route)
if (redirectTo) {
location.assign(redirectTo)
location.assign(joinURL(context.base, redirectTo))
}
}
}
8 changes: 5 additions & 3 deletions test/browser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ describe(`${browserString}, target: static, trailingSlash: true`, () => {
})
})

describe(`${browserString} (generate)`, () => {
describe(`${browserString} (generate, with router base)`, () => {
/** @type {import('playwright-chromium').ChromiumBrowser} */
let browser
/** @type {import('playwright-chromium').Page} */
Expand All @@ -187,12 +187,14 @@ describe(`${browserString} (generate)`, () => {
let server

beforeAll(async () => {
const base = '/nuxt/'
const distDir = resolve(__dirname, 'fixture', 'basic', '.nuxt-generate')
const overrides = {
generate: { dir: distDir }
generate: { dir: distDir },
router: { base }
}
await generate(loadConfig(__dirname, 'basic', overrides, { merge: true }))
server = await startHttpServer({ path: distDir, verbose: true })
server = await startHttpServer({ path: distDir, base, verbose: true })
browser = await createBrowser()
})

Expand Down
59 changes: 29 additions & 30 deletions test/utils/http-server-internal.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,49 @@
import fs from 'fs'
import http from 'http'
import { resolve } from 'path'
import { ArgumentParser } from 'argparse'
import express from 'express'
import serveStatic from 'serve-static'
import finalhandler from 'finalhandler'

/**
* Starts a server.
*
* @param {string} path
* @param {number} port
* @param {string} base
* @param {boolean} noTrailingSlashRedirect
* @param {boolean} verbose
*
* @return {import('http').Server}
*/
function startServer (path, port, noTrailingSlashRedirect, verbose) {
const serve = serveStatic(path, { redirect: !noTrailingSlashRedirect, extensions: ['html'] })
const server = http.createServer((req, res) => {
const done = finalhandler(req, res)
function startServer (path, port, base, noTrailingSlashRedirect, verbose) {
const app = express()

const next = () => {
if (req.method === 'GET') {
// When requesting /fr and both /fr/ (without index.html) and /fr.html exist, fallback to fr.html.
fs.readFile(`${resolve(path)}${req.url}.html`, function (error, buffer) {
if (error) {
done(false)
return
}
// @ts-ignore
app.use(base, serveStatic(path, { redirect: !noTrailingSlashRedirect, extensions: ['html'] }))
app.use((req, res, next) => {
if (req.method === 'GET') {
// When requesting /fr and both /fr/ (without index.html) and /fr.html exist, fallback to fr.html.
fs.readFile(`${resolve(path)}${req.url}.html`, function (error, buffer) {
if (error) {
next()
return
}

res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.end(buffer)
})
} else {
done(false)
}
res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.end(buffer)
})
} else {
next()
}

// @ts-ignore
serve(req, res, next)
})

app.on('error', error => console.error(error))

const host = 'localhost'
server.on('error', error => console.error(error))
server.listen(port, host, () => {
return app.listen(port, host, () => {
if (verbose) {
// eslint-disable-next-line no-console
console.info(`Static server started on http://${host}:${port}`)
}
})

return server
}

const parser = new ArgumentParser()
Expand All @@ -66,6 +59,12 @@ parser.add_argument('-p', '--port', {
help: 'Port to run on (default: 3000)'
})

parser.add_argument('--base', {
type: 'str',
default: '/',
help: 'The base path to expose the files at'
})

parser.add_argument('--no-trailing-slash-redirect', {
action: 'store_true',
default: false,
Expand All @@ -81,7 +80,7 @@ parser.add_argument('-v', '--verbose', {
const args = parser.parse_args()

/** @type {import('http').Server | null} */
let server = startServer(args.path, args.port, args.no_trailing_slash_redirect, args.verbose)
let server = startServer(args.path, args.port, args.base, args.no_trailing_slash_redirect, args.verbose)

process.on('SIGTERM', () => {
if (server) {
Expand Down
9 changes: 6 additions & 3 deletions test/utils/web-server.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { resolve } from 'path'
import getPort from 'get-port'
import { joinURL } from 'ufo'
import { setup as setupDevServer, teardown as teardownDevServer } from 'jest-dev-server'

/** @typedef {{
* path: string
* port?: number
* base?: string
* noTrailingSlashRedirect?: boolean
* verbose?: boolean
* }} ServerOptions
Expand All @@ -16,6 +18,7 @@ import { setup as setupDevServer, teardown as teardownDevServer } from 'jest-dev
export class StaticServer {
/** @param {ServerOptions} options */
constructor (options) {
this.base = options.base || '/'
this.path = options.path
this.url = ''
this.port = options.port || null
Expand All @@ -25,18 +28,18 @@ export class StaticServer {

/** @param {string} path */
getUrl (path) {
return `${this.url}${path}`
return joinURL(this.url, path)
}

async start () {
if (!this.port) {
this.port = await getPort()
}

this.url = `http://localhost:${this.port}`
this.url = `http://localhost:${this.port}${this.base}`

const serverPath = resolve(__dirname, 'http-server-internal.js')
const args = [`jiti ${serverPath}`, this.path, `--port ${this.port}`]
const args = [`jiti ${serverPath}`, this.path, `--port ${this.port}`, `--base ${this.base}`]

if (this.verbose) {
args.push('--verbose')
Expand Down
Loading

0 comments on commit 75b7c6e

Please sign in to comment.