Koa: redirect function doesn't work

Created on 14 Jul 2017  ·  4Comments  ·  Source: koajs/koa

I'm just trying to redirect page to user page after signup, when I use ctx.redirect, all the function does is just sending GET request to the url and not actually redirect the tab to the url from where It was.. Here's code.

signup

router.post('/signup', async (ctx, next) => {
    let data = ctx.request.body
    const param = await makeParam(data)

    try {
        const user = new User(param)
        await user.save()
        ctx.redirect(`/u/${data.username}`)
    } catch (e) {
        console.error("Failed to save post request", e, param)
    }
})

Let's say username was edqwedqwedqwed, then it's supposed to redirect the page to /u/edqwedqwedqwed but as you can see below It only sends GET request to the url and does nothing

  --> POST /signup 302 131ms 65b
  <-- GET /u/edqwedqwedqwed
  --> GET /u/edqwedqwedqwed 200 806ms 25.52kb
question

Most helpful comment

post请求发送的数据通常作为request的body发送,但无论是Node.js提供的原始request对象,还是koa提供的request对象,都不提供解析request的body的功能!
We need a middleware to parse the original request:
npm install koa-bodyparser
app.use(require('koa-bodyparser')());
Add those code before you use POST.

All 4 comments

not sure I understand. that flow looks correct if a user signs up from the browser using a plain old HTTP POST via form.

Can this be a browser settings issue?

I don't see anything wrong on the log you have given and this is how redirect works.
A simple process includes:
When a user sends a POST request via plain old HTTP POST form:
<-- POST /signup

Then the request gets processed by your route and returns a 302 redirect status.
--> POST /signup 302 131ms 65b

Your browser receives something similar to the snippet below, which basically tells the browser to redirect to the Location given on the header.

HTTP/1.1 302 Found
Vary: Accept-Encoding
Location: /u/edqwedqwedqwed
Content-Type: text/html; charset=utf-8
Content-Length: 49

Once your browser receives this, it will make a GET request to the specified url and then display it to the user.

<-- GET /u/edqwedqwedqwed
--> GET /u/edqwedqwedqwed 200 806ms 25.52kb

So basically that's how Redirect works. The only HTTP methods available are GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE. Http Request Methods
So there is no REDIRECT if that is what you meant it should do.

post请求发送的数据通常作为request的body发送,但无论是Node.js提供的原始request对象,还是koa提供的request对象,都不提供解析request的body的功能!
We need a middleware to parse the original request:
npm install koa-bodyparser
app.use(require('koa-bodyparser')());
Add those code before you use POST.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SteveCruise picture SteveCruise  ·  5Comments

ElegantScripting picture ElegantScripting  ·  5Comments

ke1Del picture ke1Del  ·  3Comments

coodoo picture coodoo  ·  4Comments

SteveCruise picture SteveCruise  ·  3Comments