Reputation: 23
My current setup is a Node.js app set up on Heroku, which is supposed to set some cookies for my client (a React app) using Express.js like this.
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
const access_token = body.access_token,
refresh_token = body.refresh_token;
let options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, response, body) {
res.cookie('access_token',access_token, { domain: 'example.com', path: '/', expires: new Date(Date.now() + 9000000), httpOnly: false });
res.cookie('refresh_token',refresh_token,{ domain: 'example.com', path: '/', expires: new Date(Date.now() + 9000000), httpOnly: false });
res.cookie('user',body.display_name,{ domain: 'example.com', path: '/', expires: new Date(Date.now() + 9000000), httpOnly: false });
res.redirect('https://www.example.com/');
});
} else {...}}
It does set the cookies, but only in the Heroku app. The domain I give is ignored completely, which obviously results in an error when I try to read the cookies on the client side. Any advice?
Edit: Added the full function.
Upvotes: 1
Views: 6305
Reputation: 6705
Here's some very simplified working code to demonstrate cookie setting in a response to a network request:
const express = require('express')
const rp = require('request-promise-native')
const app = express();
app.get("/cookie", function(req, res) {
rp.get('https://mobilesecurity.win/sample/access_token.json').then(function(body) {
const domain = 'localhost';
const parsed = JSON.parse(body);
const access_token = parsed.access_token;
const refresh_token = parsed.refresh_token;
res.cookie('access_token',access_token, { domain: domain, path: '/', expires: new Date(Date.now() + 9000000), httpOnly: false });
res.cookie('refresh_token',refresh_token,{ domain: domain, path: '/', expires: new Date(Date.now() + 9000000), httpOnly: false });
res.status(200).json({'status':'cookies set!'})
}).catch(function(error) {
res.status(500).json({'status':'failure', error:error.message});
});
});
app.listen(8080);
Here's the result:
Note here that I used localhost
as the domain since I am running the server locally. You must use a domain that matches your hostname, or the browser will refuse to set the cookie (for security reasons).
Upvotes: 2