未验证 提交 6375026a 编写于 作者: M Markoz Peña 提交者: GitHub

Added Friendly error for res.redirect 🐝 (#15844)

## Which solves this PR

 Displaying a friendly error, when the user is only passing `statusOrUrl`(type number) and the second argument `url` is ignored.

**Example**

`res.redirect(307);` // Show friendly error

Closes: https://github.com/vercel/next.js/issues/15594
x-ref: https://github.com/vercel/next.js/pull/15603
上级 eb4be226
...@@ -235,7 +235,11 @@ export function redirect( ...@@ -235,7 +235,11 @@ export function redirect(
url = statusOrUrl url = statusOrUrl
statusOrUrl = 307 statusOrUrl = 307
} }
if (typeof statusOrUrl !== 'number' || typeof url !== 'string') {
throw new Error(
`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`
)
}
res.writeHead(statusOrUrl, { Location: url }).end() res.writeHead(statusOrUrl, { Location: url }).end()
return res return res
} }
......
export default (req, res) => {
res.redirect(307)
}
export default (req, res) => {
res.redirect(null)
}
...@@ -236,6 +236,20 @@ function runTests(dev = false) { ...@@ -236,6 +236,20 @@ function runTests(dev = false) {
expect(data).toEqual({ message: 'Parsed body' }) expect(data).toEqual({ message: 'Parsed body' })
}) })
it('should show friendly error for invalid redirect', async () => {
await fetchViaHTTP(appPort, '/api/redirect-error', null, {})
expect(stderr).toContain(
`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`
)
})
it('should show friendly error in case of passing null as first argument redirect', async () => {
await fetchViaHTTP(appPort, '/api/redirect-null', null, {})
expect(stderr).toContain(
`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`
)
})
it('should redirect with status code 307', async () => { it('should redirect with status code 307', async () => {
const res = await fetchViaHTTP(appPort, '/api/redirect-307', null, { const res = await fetchViaHTTP(appPort, '/api/redirect-307', null, {
redirect: 'manual', redirect: 'manual',
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册