I am doing a basic authentication example. I have Node, Express, and Cookie. I make and store a cookie once the user logs in. Upon refreshing the page, I want to use the cookie to show that the user is still logged in on the response, and provide the information related to that user.
Server side:
// If I put the app.get('/'.....) up here I get the response, but not the page HTML/JS/CSS/etc...
// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));
// Here I get the page HTML/JS/CSS/etc but can't capture the cookie
app.get('/', function(req, res) {
console.log('I want to get here');
if(req.headers.cookie){
// This parses the cookies into a usable array
var incoming_cookies = cookie.parse(req.headers.cookie);
Person.find({...})
.then( function(results) {
if (weDontFindSomeone) {
console.log('user not found');
res.status(400).send('user not found');
} else {
if (incoming_cookies.uname === loggedIn.uname) {
console.log('Starting with a cookie logged in');
res.status(200).send(results);
} else {
console.log('Some other problem with cookies');
res.status(400).send('Some other problem with cookies');
}
}
})
.catch(function(error){
res.status(400).send('some other error in starting, error: ' + error);
});
} else {
res.status(200).send('Starting from scratch.');
}
});
How do I capture the cookies on the request to the homepage and use that to determine what is served to the client?
Do I put it in the JS on the client side?
If you want to suggest another node module, PLEASE show a working example in a plkr, fiddle, web page example, or the like. I do better studying working code, as it has taken me a bit long to get to this pont :)
Setting the cookie, also on the server side:
app.post('/api/login', function (req, res) {
console.log('Getting a login request');
if (weValidateTheCredentials) {
Person.find({...})
.then(function(personResults) {
if (personResults.rowCount === 0) {
res.status(400).send('user not found');
} else {
console.log('Logging in at \'/api/login\', and sending a cookie.');
// 3 hours max age
res.cookie('UID', req.body.uid, {maxAge: 10800000});
res.cookie('uname', req.body.uname, {maxAge: 10800000});
res.status(200).send(personResults);
}
})
.catch(function(error){
res.status(400).send('some other error in logging in, error: ' + error);
});
} else {
res.status(400).send('login requires a uname and pwhash');
}
});
The method with Cookie is a bit devious, you can use cookie-parser, It's made for express.
It is really simple, there is a example on the home page:
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)
// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"
Or with your code:
var cookieParser = require('cookie-parser');
// Add cookie parser
app.use(cookieParser());
app.get('/', function(req, res) {
console.log('I want to get here');
if(req.cookies){
Person.find({...})
.then( function(results) {
if (weDontFindSomeone) {
console.log('user not found');
res.status(400).send('user not found');
} else {
if (req.cookies.uname === loggedIn.uname) {
console.log('Starting with a cookie logged in');
res.status(200).send(results);
} else {
console.log('Some other problem with cookies');
res.status(400).send('Some other problem with cookies');
}
}
})
.catch(function(error){
res.status(400).send('some other error in starting, error: ' + error);
});
} else {
res.status(200).send('Starting from scratch.');
}
});
// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));
I was mixing the paradigm of what should be handled by the server and what should be handled by the client.
Using Jquery addon 'jquery-cookie-master', I can check the cookie on the request of the client side with if ($.cookie('attributeWanted')){...}
Related
I'm trying to save a variable to a text file, but if the variable isn't found when using spotifyApi.clientCredentialsGrant(), then I want my server to redirect to app.get('/error', function(req, res) {}); which displays a different webpage, but it's returning the error:
(node:11484) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I get around this error to display the webpage error.html?
I don't have access to EJS or window.location because it conflicts with other files and it's a node.js program, respectively.
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '/public', 'homepage.html'));
try {
spotifyApi.clientCredentialsGrant()
.then(function (data) {
// Save the access token so that it's used in future calls
client_cred_access_token = data.body['access_token'];
console.log(client_cred_access_token);
console.log('Client Credentials Success!');
}, function (err) {
console.log('Something went wrong when retrieving an access token', err.message);
throw err;
});
fs.writeFile("./public/client_cred_token.txt", '', function (err) {
console.log('Clearing previous access token');
});
fs.writeFile("./public/client_cred_token.txt", client_cred_access_token, function (err) {
if (err) return console.log(err);
});
fs.readFile('./public/client_cred_token.txt', function (err, data) {
if (err) throw err;
console.log("Saved Client Credentials as: %s", data)
});
}
catch (err) {
res.redirect('/error');
}
});
Key takeaway from the accepted answer is to not send any HTML/files to the server until it's confirmed which one is needed.
You are calling res.sendFile() first and then if you later get an error, you are also calling res.redirect('/error') which means you'll be trying to send two responses to one http request which triggers the error you see. You can't do that.
The solution is to call res.sendFile() at the end of all your other operations so you can then call it when successful and call res.redirect() when there's an error and thus only call one or the other.
In a difference from the other answer here, I've shown you how to code this properly using asynchronous file I/O so the design could be used in a real server designed to serve the needs of more than one user.
const fsp = require('fs').promises;
app.get('/', async function (req, res) {
try {
let data = await spotifyApi.clientCredentialsGrant();
// Save the access token so that it's used in future calls
client_cred_access_token = data.body['access_token'];
console.log(client_cred_access_token);
console.log('Client Credentials Success!');
await fsp.writeFile("./public/client_cred_token.txt", client_cred_access_token);
let writtenData = await fsp.readFile('./public/client_cred_token.txt');
console.log("Saved Client Credentials as: %s", writtenData);
res.sendFile(path.join(__dirname, '/public', 'homepage.html'));
} catch (err) {
console.log(err);
res.redirect('/error');
}
});
app.get('/', function (req, res) {
try {
spotifyApi.clientCredentialsGrant().then(function (data) {
// Save the access token so that it's used in future calls
let client_cred_access_token = data.body['access_token'];
console.log(client_cred_access_token);
console.log('Client Credentials Success!');
// truncate token file
fs.truncateSync("./public/client_cred_token.txt");
// write token to file
fs.writeFileSync("./public/client_cred_token.txt", client_cred_access_token);
// read token from file again
// NOTE: you could use `client_cred_access_token` here
let data = fs.readFileSync('./public/client_cred_token.txt');
console.log("Saved Client Credentials as: %s", data)
// send homepage to client when no error is thrown
res.sendFile(path.join(__dirname, '/public', 'homepage.html'));
}, function (err) {
console.log('Something went wrong when retrieving an access token', err.message);
throw err;
});
} catch (err) {
res.redirect('/error');
}
});
I swapped all asynchron file opreations with the syncron one.
They throw an error and you dont have to deal with callback chain/flow.
Also i moved the sendFile(...) at the botom in the try block, so when a error is thrown from any syncrhonus function call the sendFile is not reached, and your redirect can be sent to the client.
Otherwise you would send the homepage.html to the client, with all headers, and a redirect is not possible.
I am trying to set up a node.js server to validate receipts from AppStore connect In App Purchases I have set up. I have followed this https://github.com/voltrue2/in-app-purchase library but I'm getting an error response saying my receipt is not defined and failed to validate receipt. I'm I doing anything wrong here. I'm still testing on a local server. I want to get it to work before hosting it on Heroku. What would I be doing wrong here?
const iap = require('in-app-purchase');
iap.config({
applePassword: 'MySecretKey',
test: true
});
iap.setup()
.then(() => {
iap.validateOnce(receipt, appleSecretString).then(onSuccess).catch(onError);
})
.catch((error) => {
if (error) {
console.log('Validation error' + error);
}
});
iap.validate(iap.APPLE, function (error, appleResponse) {
console.log(iap.APPLE);
if (error) {
console.log('Failed to validate receipt' + error);
}
if (iap.isValidated(appleResponse)) {
console.log('Validation successful');
}
});
Here are the logs
iapserver:server Listening on port 3000 +0ms
Validation errorReferenceError: receipt is not defined
apple
Failed to validate receiptError: failed to validate purchase
From the error is seems like you're not actually passing the receipt file into the validateOnce function. Somewhere before that code runs you need to set:
const receipt = req.query.receipt;
And invoke your API with something like:
http://localhost:3000/verifyReceipt?receipt=<YOUR_RECEIPT_DATA>
You can verify your receipt beforehand manually to make sure it's valid.
Putting this all together, you'd get something like:
var express = require('express');
var app = express();
const iap = require('in-app-purchase');
app.get('/verifyReceipt', function(req, res){
const receipt = req.query.receipt;
iap.config({
applePassword: 'MySecretKey',
test: true
});
iap.setup()
.then(() => {
iap.validateOnce(receipt, appleSecretString).then(onSuccess).catch(onError);
})
.catch((error) => {
if (error) {
console.log('Validation error' + error);
res.status(400).send({valid: false});
}
});
iap.validate(iap.APPLE, function (error, appleResponse) {
console.log(iap.APPLE);
if (error) {
console.log('Failed to validate receipt' + error);
res.status(400).send({valid: false});
}
if (iap.isValidated(appleResponse)) {
console.log('Validation successful');
res.status(200).send({valid: true});
}
});
});
app.listen(3000);
Note that this will only verify the receipt at purchase, if you're implementing subscriptions you also need to periodically refresh the receipt to make sure they user didn't cancel. Here's a good guide on implementing subscriptions: iOS Subscriptions are Hard
I want to make an api that will serve files of any extensions.
Like this: http://localhost/download/[file].[extension]
Here is my code, but it is intermittently giving this message: Can't set headers after they are sent.
var express = require('express');
var app = express();
app.get('/download/:fileName/:extension', function(req, res){
var file = __dirname + '/' + req.params.fileName + '.' + req.params.extension;
res.download(file, function(err){
if (err) {
res.sendStatus(404);
}
res.end();
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('app listening at http://%s:%s', host, port);
});
res.download has already sent a response (Not always true in the case of an error though)
You can fix this by doing
res.download(file, function(err){
if(err) {
// Check if headers have been sent
if(res.headersSent) {
// You may want to log something here or do something else
} else {
return res.sendStatus(SOME_ERR); // 404, maybe 500 depending on err
}
}
// Don't need res.end() here since already sent
}
Other changes called out in the comments above:
download uses sendFile, which you don't need res.end() after
download's documentation warns that you need to check res.headersSent when handling errors, as the headers may already be sent, which would mean you can't change the status
I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong
I'm trying to authenticate with OAuth on NodeJS and I'm getting this error:
Error getting OAuth request token : { statusCode: 401, data: '\n\n Desktop applications only support the oauth_callback value \'oob\'\n /oauth/request_token\n\n' }
Here is my code (server.js)
var express = require('express');
var util = require('util');
var oauth = require('oauth');
var app = express.createServer();
// Get your credentials here: https://dev.twitter.com/apps
var _twitterConsumerKey = "1";
var _twitterConsumerSecret = "2";
var consumer = new oauth.OAuth(
"https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token",
_twitterConsumerKey, _twitterConsumerSecret, "1.0A", "http://127.0.0.1:8080/sessions/callback", "HMAC-SHA1");
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.session({ secret: "very secret" }));
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
});
app.get('/sessions/connect', function(req, res){
consumer.getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret, results){
if (error) {
res.send("Error getting OAuth request token : " + util.inspect(error), 500);
} else {
req.session.oauthRequestToken = oauthToken;
req.session.oauthRequestTokenSecret = oauthTokenSecret;
res.redirect("https://twitter.com/oauth/authorize?oauth_token="+req.session.oauthRequestToken);
}
});
});
app.get('/sessions/callback', function(req, res){
util.puts(">>"+req.session.oauthRequestToken);
util.puts(">>"+req.session.oauthRequestTokenSecret);
util.puts(">>"+req.query.oauth_verifier);
consumer.getOAuthAccessToken(req.session.oauthRequestToken, req.session.oauthRequestTokenSecret, req.query.oauth_verifier, function(error, oauthAccessToken, oauthAccessTokenSecret, results) {
if (error) {
res.send("Error getting OAuth access token : " + util.inspect(error) + "["+oauthAccessToken+"]"+ "["+oauthAccessTokenSecret+"]"+ "["+util.inspect(results)+"]", 500);
} else {
req.session.oauthAccessToken = oauthAccessToken;
req.session.oauthAccessTokenSecret = oauthAccessTokenSecret;
res.redirect('/home');
}
});
});
app.get('/home', function(req, res){
consumer.get("http://twitter.com/account/verify_credentials.json", req.session.oauthAccessToken, req.session.oauthAccessTokenSecret, function (error, data, response) {
if (error) {
res.redirect('/sessions/connect');
// res.send("Error getting twitter screen name : " + util.inspect(error), 500);
} else {
var parsedData = JSON.parse(data);
// req.session.twitterScreenName = response.screen_name;
res.send('You are signed in: ' + parsedData.screen_name);
}
});
});
app.get('*', function(req, res){
res.redirect('/home');
});
app.listen(8080);
Thanks in advance.
Fill up the "Callback URL" field in your Twitter settings dev account.
In addition to what the other answer says...
I kept getting an error when trying to fill up the Callback URL in the Twitter dev console. I was trying to enter http://localhost:4000, but it was giving me errors. If you need to need to use localhost, you can use http://127.0.0.1:4000 instead, and Twitter accepts that.
(Maybe obvious to some, but took me a little while to figure it out.)
This is an old question, but I ran into this error today, and the thing I noticed is that NEW Twitter applications can be saved WITHOUT a callback URL, but as soon as you save your app with a callback URL, Twitter won't let you save it -- it will revert to the last URL you had. In our case, it didn't matter since our OAuth flow supplies the callback URL, but something on Twitter's side of things REQUIRES that there be a callback URL (ANY callback URL). So in our case, this error cropped up only in dev environments that had a new (and unused) Twitter application associated with them.
Just came across this today, hope it helps others.
If you are trying to authenticate Twitter API Authentication through Firebase.
It is mandatory that you should add the Callback URLs (required field)
in the Authentication Section of your Twitter API Developer
Portal.
You can find the Callback Url from your Firebase Console in the Authentication Section (Sign-in methods) Authentication provider for Twitter.
Make sure that the Callback Urls to be exactly the same.
If not, it will give you a error similar to this:
com.firebase.ui.auth.FirebaseUiException: There was an internal error in the web widget. [ {"code":"auth/invalid-credential","message":"Error getting request token: 403 <?xml version='1.0' encoding='UTF-8'?><errors><error code=\"415\">Callback URL not approved for this client application. Approved callback URLs can be adjusted in your application settings</error></errors>.