request如何继续使用上一次请求返回的cookie?

客户端
import request from 'request-promise'


request('http://localhost:8090/').then(res => {
    console.log(res)
})

request('http://localhost:8090/').then(res => {
    console.log(res)
})

request('http://localhost:8090/').then(res => {
    console.log(res)
})
服务端
const Koa = require('koa')
const route = require('koa-route')
const bodyParser = require('koa-bodyparser')

const app = new Koa()

app.use(bodyParser({
    enableTypes: ['json', 'form', 'text']
}))

const main = ctx => {
    ctx.cookies.set('mycookie', 'hello-value');
    console.log(ctx.cookies.get('mycookie'))
    // 奇怪,这里为什么输出 undefined 呢?
    
    ctx.response.type = 'html'
    ctx.response.body = '<a href="/">main Page</a>'
}

app.use(route.get('/', main))
app.listen(8090, '0.0.0.0', () => {
    console.log('Example app listening on http://localhost:8090/')
})
问题

这里明明设置了cookie,但是输出 undefined ? 用浏览器就能正常的输出 hello-value

   ctx.cookies.set('mycookie', 'hello-value');
   console.log(ctx.cookies.get('mycookie'))
   console.log(ctx.cookies.get('mycookie')
阅读 3.7k
2 个回答

请先明白 cookie 是什么以及它的作用,再思考下为什么这里为 undefined

你这里的 set 是设置的是响应给客户端的 cookie 设置,而 get 是获取当前客户端请求的 cookie,因此只有在下一个请求才能获取到你当前设置的 cookie 的值。

你这里自己刚设置的,就去取?cookie一般都是在亲求信息的适合获取的,你在其它请求接口下应该是能正常获取的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题