Reputation: 3808
I am trying to create cookies, but I am not seeing any cookie in browser. Instead of that I am getting different output on Postman & different output on chrome browser.
blow is how I code to create cookies.
Create route
drop.get("create", handler:createCookie)
Handler
func createCookie(request: Request) throws -> ResponseRepresentable {
let cookie = Cookie(name: "login", value:"value", expires: generateExpirationDate(), secure: true)
request.cookies.insert(cookie)
return "Done"
}
below is func to create expiration handler
func generateExpirationDate() -> Date {
return Date() + (60 * 1) // 1 Minutes later
}
In post man I am getting one cookie named "vapor-sessions"
And in chrome browser I am getting two cookies as in below picture.
But my desired one is not there. !!!!!!!
EDIT:
I also have tried below code but no luck for Postman, but this one 'works in chrome', I have doubt for other browsers !!!!
func createCookie(request: Request) throws -> ResponseRepresentable {
let cookie = Cookie(name: "login", value:"value", expires: generateExpirationDate(), secure: true)
let response = try Response(status: .ok, json: JSON(node: [
"yo": "yoyo"
]))
response.cookies.insert(cookie)
return response
}
Upvotes: 3
Views: 1410
Reputation: 2328
on local environment the cookies not run, I had same problem with Postman, you can try on real environment, for example with Heroku, it's free.
Maybe for you test cookies that use Postman application Interceptor Cookies plugin.
This code works for me, I'm using Middleware controller for set cookie..
let auth = AuthMiddleware(user: User.self) { value in
return Cookie(
name: "your_cookie_name",
value: value,
expires: Date().addingTimeInterval(60 * 60 * 5), // 5 hours
secure: true,
httpOnly: true
)
}
drop.middleware.append(auth)
I hope I've been helpful
Upvotes: 2
Reputation: 5421
Your pre-edit code is not working because you are adding the cookie to the request
, not the response
. The response is what is sent to the browser, so that is the right place to set the cookie.
Here is a full example:
import Foundation
import Cookies
import HTTP
import Vapor
let drop = Droplet()
drop.get("create") { request in
let response = Response(status: .ok)
let expiry = Date(timeIntervalSinceNow: 60)
let cookie = Cookie(name: "login", value: "value", expires: expiry)
response.cookies.insert(cookie)
return response
}
drop.run()
Using curl
to check the headers sent by Vapor, you can clearly see where the cookie is being set.
HTTP/1.1 200 OK
Set-Cookie: login=value; Expires=Sat, 14 Jan 2017 05:31:32 GMT; Path=/
Date: Sat, 14 Jan 2017 05:30:32 GMT
Content-Length: 0
Upvotes: 3