meteor facebook error 666 - facebook
I have a project that is getting big, and I'm trying to login with meteor accounts-facebook package, but it shows error 666
I have already complete access to facebook info about the user trying to login but when Accounts.validateLoginAttempt() is called it returns an error with code 666
I've never seen that kind of error and there's nothing anywhere about that!
Here are my logs:
I20170509-09:14:53.403(-3)? ***options onCreateUser { profile: { name: 'Rafael Melo' } }
I20170509-09:14:53.420(-3)? ***user onCreateUser { createdAt: Tue May 09 2017 09:14:53 GMT-0300 (Hora Padrão da Bahia),
I20170509-09:14:53.421(-3)? _id: 'S7a78CctLco7pddTQ',
I20170509-09:14:53.421(-3)? services:
I20170509-09:14:53.421(-3)? { facebook:
I20170509-09:14:53.422(-3)? { accessToken: 'xxxxxx',
I20170509-09:14:53.422(-3)? expiresAt: 1499436988665,
I20170509-09:14:53.423(-3)? id: 'xxxx',
I20170509-09:14:53.423(-3)? email: 'xxx#xxx.com',
I20170509-09:14:53.424(-3)? name: 'Rafael Melo',
I20170509-09:14:53.424(-3)? first_name: 'Rafael',
I20170509-09:14:53.440(-3)? last_name: 'Melo',
I20170509-09:14:53.441(-3)? link: 'https://www.facebook.com/app_scoped_user_id/xxxxx/',
I20170509-09:14:53.448(-3)? gender: 'male',
I20170509-09:14:53.454(-3)? locale: 'en_US',
I20170509-09:14:53.456(-3)? age_range: [Object] } } }
I20170509-09:14:53.840(-3)? ********Results? { statusCode: 200,
I20170509-09:14:53.841(-3)? content: '{"first_name":"Rafael","last_name":"Melo","picture":{"data":{"is_silhouette":false,"url":"https:\\/\\/scontent.xx.fbcdn.net\\/v\\/t1.0-1\\/p50x50\\/xxxxx.jpg?oh=xxxx&oe=xxxx"}},"email":"xxx\\u0040xxxxx.com","gender":"male","locale":"en_US","link":"https:\\/\\/www.facebook.com\\/app_scoped_user_id\\/xxx\\/","id":"xxx"}',
I20170509-09:14:53.842(-3)? headers:
I20170509-09:14:53.842(-3)? { 'access-control-allow-origin': '*',
I20170509-09:14:53.843(-3)? etag: '"3befwqdwqd7b4198656bb0c5cb"',
I20170509-09:14:53.844(-3)? pragma: 'no-cache',
I20170509-09:14:53.845(-3)? 'cache-control': 'private, no-cache, no-store, must-revalidate',
I20170509-09:14:53.847(-3)? 'x-fb-rev': '303217',
I20170509-09:14:53.848(-3)? 'content-type': 'text/javascript; charset=UTF-8',
I20170509-09:14:53.848(-3)? 'x-fb-trace-id': 'wqsdsa2mf9/',
I20170509-09:14:53.850(-3)? 'facebook-api-version': 'v2.7',
I20170509-09:14:53.862(-3)? expires: 'Sat, 01 Jan 2000 00:00:00 GMT',
I20170509-09:14:53.862(-3)? vary: 'Accept-Encoding',
I20170509-09:14:53.865(-3)? 'x-fb-debug': '2esdwqdasd/asdqdwqdqwd==',
I20170509-09:14:53.866(-3)? date: 'Tue, 09 May 2017 12:14:52 GMT',
I20170509-09:14:53.867(-3)? connection: 'close' },
I20170509-09:14:53.868(-3)? data:
I20170509-09:14:53.868(-3)? { first_name: 'Rafael',
I20170509-09:14:53.869(-3)? last_name: 'Melo',
I20170509-09:14:53.879(-3)? picture: { data: [Object] },
I20170509-09:14:53.880(-3)? email: 'xxxx#xxxx.com',
I20170509-09:14:53.881(-3)? gender: 'male',
I20170509-09:14:53.881(-3)? locale: 'en_US',
I20170509-09:14:53.882(-3)? link: 'https://www.facebook.com/app_scoped_user_id/xxxxxxxxxxx/',
I20170509-09:14:53.883(-3)? id: 'xxxxxxxxxxx' } }
I20170509-09:14:53.996(-3)? *****attempt { type: 'unknown',
I20170509-09:14:53.997(-3)? allowed: false,
I20170509-09:14:53.998(-3)? methodName: 'login',
I20170509-09:14:53.999(-3)? methodArguments: [ { oauth: [Object] } ],
I20170509-09:14:53.999(-3)? error:
I20170509-09:14:54.000(-3)? { [Error: {"_id":"S7a78CctLco7pddTQ","services":{"facebook":{"accessToken":"23dscxxxxxxxxxxxxxxxx","expiresAt":1499436988665,"id":"xxxxxxxxxxx","email":"xxxx#xxxx.com","name":"Rafael Melo","first_name":"Rafael","last_name":"Melo","link":"https://www.facebook.com/app_scoped_user_id/xxxxxxxxxxx/","gender":"male","locale":"en_US","age_range":{"min":21}}},"emails":[{"address":"xxxx#xxxx.com","verified":true}],"profile":{"nome":"Rafael Melo","sexo":"Masculino"},"email":"xxxx#xxxx.com"} [666]]
I20170509-09:14:54.001(-3)? error: 666,
I20170509-09:14:54.001(-3)? reason: '{"_id":"S7a78CctLco7pddTQ","services":{"facebook":{"accessToken":"23dscxxxxxxxxxxxxxxxx","expiresAt":1499436988665,"id":"xxxxxxxxxxx","email":"xxxx#xxxx.com","name":"Rafael Melo","first_name":"Rafael","last_name":"Melo","link":"https://www.facebook.com/app_scoped_user_id/xxxxxxxxxxx/","gender":"male","locale":"en_US","age_range":{"min":21}}},"emails":[{"address":"xxxx#xxxx.com","verified":true}],"profile":{"nome":"Rafael Melo","sexo":"Masculino"},"email":"xxxx#xxxx.com"}',
I20170509-09:14:54.002(-3)? details: undefined,
I20170509-09:14:54.003(-3)? message: '{"_id":"S7a78CctLco7pddTQ","services":{"facebook":{"accessToken":"23dscxxxxxxxxxxxxxxxx","expiresAt":1499436988665,"id":"xxxxxxxxxxx","email":"xxxx#xxxx.com","name":"Rafael Melo","first_name":"Rafael","last_name":"Melo","link":"https://www.facebook.com/app_scoped_user_id/xxxxxxxxxxx/","gender":"male","locale":"en_US","age_range":{"min":21}}},"emails":[{"address":"xxxx#xxxx.com","verified":true}],"profile":{"nome":"Rafael Melo","sexo":"Masculino"},"email":"xxxx#xxxx.com"}',
I20170509-09:14:54.013(-3)? errorType: 'Meteor.Error' },
I am using meteor accounts-facebook package.
EDIT:
onClick:
Meteor.loginWithFacebook({
requestPermissions: ['public_profile', 'email']
}, function(error) {
if (error) {
Session.set('errorMessage', error.reason || 'Unknown error');
console.log("error", Session.get('errorMessage'));
} else {
console.log("Succeso FB!!")
}
});
hooks:
Accounts.onCreateUser(function (options, user) {
console.log("***options onCreateUser", options);
console.log("***user onCreateUser", user)
if (user.hasOwnProperty('services') && user.services.hasOwnProperty('facebook') ) {
let result = Meteor.http.get('https://graph.facebook.com/v2.7/' + user.services.facebook.id + '?access_token=' + user.services.facebook.accessToken + '&fields=first_name, last_name, picture, email, gender, locale, link');
console.log("********Results?", result);
let doc = {
_id: user._id,
services: user.services,
emails: [],
profile:{}
},
fullNome = result.data.first_name + " " + result.data.last_name;
doc.profile = {
index: '0',
nome: fullNome,
role: 'Usuário',
isValid: true,
isComplete: true,
imageId: '',
}
doc.emails.push({ address:result.data.email, verified: true });
console.log("***Doc no onCreateUser", doc);
Meteor.users.simpleSchema().clean(doc);
Schemas.User.validate(doc);
check(doc, Meteor.users.simpleSchema())
user = doc;
return user;
}
else{
return user;
}
});
Accounts.validateLoginAttempt(function(attempt){
console.log("*****attempt", attempt);
});
Accounts.config({
sendVerificationEmail: false,
loginExpirationInDays: 10,
forbidClientAccountCreation: false
});
PACKAGES:
accounts-base 1.2.14* A user account system
accounts-facebook 1.1.0* Login service for Facebook accounts
accounts-password 1.3.0* Password support for accounts
alanning:roles 1.2.15* Authorization package for Meteor
aldeed:autoform 5.8.1* Easily create forms with automatic insert and update, and aut...
aldeed:autoform-select2 1.0.5* Custom select2 input type for AutoForm
aldeed:collection2 2.10.0 Automatic validation of insert and update operations on the ...
aldeed:http-fix 0.2.2+ Improves the core HTTP package
aldeed:moment-timezone 0.4.0 Timezone support for moment.js, packaged for Meteor. See http...
aldeed:simple-schema 1.5.3 A simple schema validation object with reactivity. Used by co...
aldeed:template-extension 4.0.0* Adds template features currently missing from the templating ...
ashutosh:email-att 1.1.4 Send e-mails with attachments.
benjaminrh:event-hooks 1.4.3 Provides hooks for various user-triggered events
benjaminrh:jquery-cookie 0.1.0 A simple, lightweight jQuery plugin for reading, writing and ...
benjick:webcam 0.0.2 WebcamJS for Meteor
bigdsk:inputmask 3.1.63* JQuery InputMask for Meteor
cordova:cordova-plugin-android-permissions 0.10.0
cordova:cordova-plugin-camera 2.4.1
cordova:cordova-plugin-compat 1.1.0
cordova:cordova-plugin-crop-on-steroids 1.0.0
cordova:cordova-plugin-file 4.3.2
cordova:cordova-plugin-file-transfer 1.6.2
dburles:collection-helpers 1.0.4* Transform your collections with helpers that you define
dburles:google-maps 1.1.5 Google Maps Javascript API v3
dschulz:jquery-qrcode 1.0.2 jQuery.qrcode - a jQuery plugin for dynamically generating QR...
ecmascript 0.6.2* Compiler plugin that supports ES2015+ in all .js files
email 1.1.17_1* Send email messages
es5-shim 4.6.15 Shims and polyfills to improve ECMAScript 5 support
fortawesome:fontawesome 4.5.0* Font Awesome (official): 500+ scalable vector icons, customiz...
francocatena:status 1.5.3 Displays the connection status between browser and server
gadicohen:phantomjs 0.0.2 phantomjs installation script; wrapper for node phantomjs pac...
gibson:meteor-autonumeric 0.0.2 Add jquery-autoNumeric library support
ground:db 0.3.15 Ground Meteor.Collections offline
hilios:jquery.countdown 2.0.4 The Final Countdown plugin for jQuery
http 1.2.11* Make HTTP calls to remote servers
iron:router 1.0.13* Routing specifically designed for Meteor
jaywon:meteor-node-uuid 1.0.1 Generate RFC compliant UUIDs using node-uuid.
jeremy:selectize 0.12.1_5 Selectize is a hybrid of a textbox and <select> element us...
jesperwe:bootstrap-select 1.7.4_4 Meteor wrapper for http://silviomoreto.github.io/bootstrap-...
jparker:crypto-md5 0.1.1 MD5 algorithm for CryptoJS, standard secure algorithms
jquery 1.11.9* Manipulate the DOM using CSS selectors
kadira:debug 3.2.2 Full Stack Debugging Solution for Meteor
kadira:dochead 1.5.0 Isomorphic way to manipulate document.head for Meteor apps
kevohagan:sweetalert 1.0.0 a beautiful replacement for javascript's alert()
lepozepo:accounting 1.0.0 Accounting.js - number, money and currency formatting - full...
lukemadera:social-share 1.2.0 Cross platform (inc. Cordova) social sharing for facebook, tw...
markoshust:owl-carousel-2 2.0.0-beta.3a Owl Carousel 2
matb33:collection-hooks 0.8.4 Extends Mongo.Collection with before/after hooks for insert/u...
matteodem:easy-search 2.0.0 Easy-to-use search with Blaze Components (+ Elastic Search su...
meteor-base 1.0.4 Packages that every Meteor app needs
meteor-platform 1.2.6 (Deprecated) Include a standard set of Meteor packages in you...
meteorhacks:aggregate 1.3.0 Proper MongoDB aggregations support for Meteor
meteorhacks:async 1.0.0 Set of async utilities to work with NPM modules and other asy...
meteorhacks:kadira 2.30.0* Performance Monitoring for Meteor
meteorhacks:npm 1.5.0 Use npm modules with your Meteor App
meteorhacks:picker 1.0.3 Server Side Router for Meteor
meteorhacks:ssr 2.2.0 Server Side Rendering for Meteor with Blaze
meteorhacks:subs-manager 1.6.4 Subscriptions Manager for Meteor
meteorhacks:zones 1.6.0 Zone.Js integration for meteor
meteortoys:allthings 3.0.0 Insanely Handy Development Tools
mizzao:autocomplete 0.5.1 Client/server autocompletion designed for Meteor's collection...
mobile-experience 1.0.4 Packages for a great mobile user experience
mologie:reactive-selectize 0.1.5 Keeps selectize.js's options in sync with a reactive data source
momentjs:moment 2.14.4* Moment.js (official): parse, validate, manipulate, and displ...
mongo 1.1.15* Adaptor for using MongoDB and Minimongo over DDP
mrt:external-file-loader 0.1.4 The External File Loader package helps easily load external j...
mystor:device-detection 0.2.0 Client-Side Device Type Detection & Template Switching with O...
natestrauser:select2 3.5.1* Select2 is a jQuery based replacement for select boxes.
nicolaslopezj:excel-export 1.0.0 Export data to excel
numeral:numeral 1.5.3_1 Numeral.js (official) - A library for formatting and manipu...
peerlibrary:fs 0.1.7 fs node.js module with fiber-enabled synchronous functions
peppelg:bootstrap-3-modal 1.0.4 Simple usage of bootstrap 3 modals.
percolate:momentum-iron-router 0.7.0 A momentum plugin for transitioning Iron Router pages
praxie:canvas-to-blob 1.1.1 JavaScript Canvas to Blob is a function to convert canvas ele...
raix:handlebar-helpers 0.2.5 Handlebar helpers
rajit:bootstrap3-datepicker 1.5.1* Meteor packaging of eternicode/bootstrap-datepicker for Boots...
rajit:bootstrap3-datepicker-pt-br 1.5.1* Meteor packaging of Brazilian translation of eternicode/boots...
reactive-var 1.0.10* Reactive variable
reywood:publish-composite 1.4.2* Publish a set of related documents from multiple collections ...
rzymek:moment-locale-pt-br 2.12.0* Moment.js pt-br locale. Companion package for rzymek:moment
sacha:spin 2.3.1 Simple spinner package for Meteor
sergeyt:typeahead 0.11.1_9 Autocomplete package for meteor powered by twitter typeahe...
service-configuration 1.0.11 Manage the configuration for third-party services
session 1.1.6* Session variable
sewdn:jquery-cropper 1.0.0_1 Fengyuan Chen's terrific jQuery plugin for cropping/zooming...
shell-server 0.2.1* Server-side component of the `meteor shell` command.
spiderable 1.0.13 Makes the application crawlable to web spiders
standard-minifier-css 1.2.0_1* Standard css minifier used with Meteor apps by default.
standard-minifier-js 1.2.0_1* Standard javascript minifiers used with Meteor apps by defa...
summernote:summernote 0.8.1 summernote (official): jQuery+Bootstrap WYSIWYG editor with e...
tracker 1.1.2* Dependency tracker to allow reactive callbacks
tsega:bootstrap3-datetimepicker 4.17.37_1 Bootstrap 3 DateTime picker from #Eonasdan, packaged for ...
twbs:bootstrap 3.3.6 The most popular front-end framework for developing responsiv...
u2622:persistent-session 0.4.4 Persistently store Session data on the client
usefulio:sync-methods 0.2.0 Adds Meteor.syncMethods that lets you call an asynchonous ser...
vsivsi:file-collection 1.3.6* Collections that efficiently store files using MongoDB GridFS...
williamledoux:bootstrap-toggle 2.2.1 Bootstrap Toggle Meteor component
xmlbuilder 2.5.14* An XML builder for node.js similar to java-xmlbuilder.
yogiben:autoform-modals 0.3.8 Create, update and delete collections with modals
yogiben:helpers 0.0.6 Meteor helpers that should come as standard
zimme:active-route 2.0.4_1* Active route helpers
zimme:select2-bootstrap3-css 1.4.6 CSS to make Select2 fit in with Bootstrap 3
Accounts.validateLoginAttempt will drop the login attempt if faulsy value returned. More about that https://docs.meteor.com/api/accounts-multi.html#AccountsServer-validateLoginAttempt
So in your case if you want to just show the results, you should do
Accounts.validateLoginAttempt(function(attempt){
console.log("*****attempt", attempt);
return true;
});
Second, there was some changes in Facebook API (we even had an internal server error because of that!), so I recommend to update to the latest accounts-facebook:
meteor update accounts-facebook
If update didn't change the version, update it manually via editing the .meteor/versions file
Related
Caching external downloads with Workbox
I'm working on a GatsbyJS site using gatsby-plugin-offline which is available at example.com and would like to make PDF files to which I link on example.com but are at download.example.com/example.pdf available offline. Is that possible?
Yes, it's possible. I'm not 100% familiar with gatsby-plugin-offline's configuration, but it looks like https://www.gatsbyjs.org/packages/gatsby-plugin-offline/#available-options describes a process for appending additional service worker logic to thee end of its default configuration: plugins: [{ resolve: `gatsby-plugin-offline`, options: { appendScript: require.resolve(`src/custom-sw-code.js`), }, }] Then in src/custom-sw-code.js: workbox.routing.registerRoute( ({url}) => url.pathname.endsWith('.pdf'), // Use StaleWhileRevalidate, CacheFirst, etc. as desired. new workbox.strategies.StaleWhileRevalidate({cacheName: 'pdfs'}) );
ECONNREFUSED during 'next build'. Works fine with 'next dev' [duplicate]
This question already has an answer here: Fetch error when building Next.js static website in production (1 answer) Closed last year. I have a very simple NextJS 9.3.5 project. For now, it has a single pages/users and a single pages/api/users that retrieves all users from a local MongoDB table It builds fine locally using 'next dev' But, it fails on 'next build' with ECONNREFUSED error page/users import fetch from "node-fetch" import Link from "next/link" export async function getStaticProps({ params }) { const res = await fetch(`http://${process.env.VERCEL_URL}/api/users`) const users = await res.json() return { props: { users } } } export default function Users({ users }) { return ( <ul> {users.map(user => ( <li key={user.id}> <Link href="/user/[id]" as={`/user/${user._id}`}> <a>{user.name}</a> </Link> </li> ))} </ul> ); } pages/api/users import mongoMiddleware from "../../lib/api/mongo-middleware"; import apiHandler from "../../lib/api/api-handler"; export default mongoMiddleware(async (req, res, connection, models) => { const { method } = req apiHandler(res, method, { GET: (response) => { models.User.find({}, (error, users) => { if (error) { connection.close(); response.status(500).json({ error }); } else { connection.close(); response.status(200).json(users); } }) } }); }) yarn build yarn run v1.22.4 $ next build Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade` > Info: Loaded env from .env Creating an optimized production build Compiled successfully. > Info: Loaded env from .env Automatically optimizing pages .. Error occurred prerendering page "/users". Read more: https://err.sh/next.js/prerender-error: FetchError: request to http://localhost:3000/api/users failed, reason: connect ECONNREFUSED 127.0.0.1:3000 Any ideas what is going wrong ? particularly when it works fine with 'next dev' ? Thank you.
I tried the same few days ago and didn't work... because when we build the app, we don't have localhost available... check this part of the doc - https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly - that said: "You should not fetch an API route from getStaticProps..." - (Next.js 9.3.6)
Just to be even more explicit on top of what Ricardo Canelas said: When you do next build, Next goes over all the pages it detects that it can build statically, i.e. all pages that don't define getServerSideProps, but which possibly define getStaticProps and getStaticPaths. To build those pages, Next calls getStaticPaths to decide which pages you want to build, and then getStaticProps to get the actual data needed to build the page. Now, if in either of getStaticPaths or getStaticProps you do an API call, e.g. to a JSON backend REST server, then this will get called by next build. However, if you've integrated both front and backend nicely into a single server, chances are that you have just quit your development server (next dev) and are now trying out a build to see if things still work as sanity check before deployment. So in that case, the build will try to access your server, and it won't be running, so you get an error like that. The correct approach is, instead of going through the REST API, you should just do database queries directly from getStaticPaths or getStaticProps. That code never gets run on the client anyways, only server, to it will also be slightly more efficient than doing a useless trip to the API, which then calls the database indirectly. I have a demo that does that here: https://github.com/cirosantilli/node-express-sequelize-nextjs-realworld-example-app/blob/b34c137a9d150466f3e4136b8d1feaa628a71a65/lib/article.ts#L4 export const getStaticPathsArticle: GetStaticPaths = async () => { return { fallback: true, paths: (await sequelize.models.Article.findAll()).map( article => { return { params: { pid: article.slug, } } } ), } } Note how on that example, both getStaticPaths and getStaticProps (here generalized HoC's for reuse, see also: Module not found: Can't resolve 'fs' in Next.js application ) do direct database queries via sequelize ORM, and don't do any HTTP calls to the external server API. You should then only do client API calls from the React components on the browser after the initial pages load (i.e. from useEffect et al.), not from getStaticPaths or getStaticProps. BTW, note that as mentioned at: What is the difference between fallback false vs true vs blocking of getStaticPaths with and without revalidate in Next.js SSR/ISR? reducing client calls as much as possible and prerendering on server greatly reduces application complexity.
How to publish a custom nuxt plugin + development workflow
I am looking for some best practices for publishing and developing nuxt plugins. I would like to write a plugin which gives our web applications the possibility to request oauth tokens from everywhere. I have written this plugin localy in my project and it works. Now my target is to move the code to a seperate plugin project and upload it to npm so every one in my company might use it easily. Are there any guides how to setup a nuxt plugin project? I found several guides for creating vue-plugins but the structure of them are a bit different to nuxt. I do not have a install method. Because my plugin simply wraps vuex store methods defined in oAuthStore.js as global methods, which can be used when I register my plugin in nuxt.config.js. Vue plugins seems to work a bit different. I upload a vue-plugin with an install method. When I try to import it and run my application on dev server (npm run dev) i always get the error message: This dependency was not found: * my-plugin in ./plugins/vuex-persisted.js friendly-errors 16:55:24 friendly-errors 16:55:24 To install it, you can run: npm install --save my-plugin My plugin has been uploaded to npm correctly and I have used it by executing npm install --save my-plugin so it has an entry on dependency list in package.json. When I try to npm-link my-plugin I get the same error. This is the only way I know for rapid prototyping because I do not want a npm publish every time I want to test something. Does everyone know a way for a better developing workflow for working on nuxt plugins? Thanks for any help. Best regards Moritz /** oAuthPlugin.js **/ import oAuthStore from './oAuthStore.js' import Cookies from 'js-cookie' import createPersistedState from 'vuex-persistedstate' export default ({store, isHMR, app}, inject) => { app.store.registerModule('oAuth', oAuthStore ); var me = app; inject('getOAuthCredentials', () => { var data = {}; if(app.$store) { var data = app.$store.getters["oAuth/getAuthCredentials"]; } return data; }); inject('requestOAuthCredentials', (data) => { if(me.store) { me.store.commit("oAuth/requestOAuthCredentials", data); } }); if (isHMR) return // add persisted state as a vue mounted mixin if (!app.mixins) { app.mixins = [] } app.mixins.push({mounted () { createPersistedState({ key: 'vuex-persisted', paths: ['oAuth'], storage: { getItem: key => Cookies.get(key), setItem: (key, value) => Cookies.set(key, value, {expires: 3}), removeItem: key => Cookies.remove(key) } })(store); }}); } /** nuxt.config.js **/ /* ** Plugins to load before mounting the App */ plugins: [ { src: '~/plugins/vuex-persisted', ssr: false }, { src: '~/plugins/oAuthPlugin.js' } ],
Does flash message (req.flash) exists in Sails 1.0.0 (beta)?
I was trying Sails.js beta version (1.0.0-46) and noticed that flash messages are not available out-of-box: req.flash(type, message) I got a TypeError: req.flash is not a function message when trying to use it.
Ouch... just found the answer right in the upgrade docs (Upgrading to v1.0). The connect-flash middleware has been removed (so req.flash() will no longer be available by default). If you wish to continue using req.flash(), run npm install --save connect-flash in your app folder and add the middleware manually. Run the command bellow: npm install --save connect-flash And modify the config/http.js file: middleware: { flash : require('connect-flash')(), order: [ 'cookieParser', 'session', 'flash', // <-- add this // 'bodyParser', 'compress', 'poweredBy', 'router', 'www', 'favicon', ],
Its in its session object req.session.flash, you can use it as req.session.flash{type:'success', message:'your message'}
Sails.js HOWTO: implement logging for HTTP requests
With the poor default logging of Sails.js not showing http request logs(even on verbose). What is the best way implement http request logging to console so i can see if I am getting malformed requests? Expressjs's default logging would be enough. I would prefer a Sails.js configuration way of doing it rather then a change the source code approach is possible. Has anyone had experience with this. My google searches seem oddly lacking information. Running Sails v0.9.8 on Mac OSX.
There's no Sails config option to log every request, but you can add a quick logging route at the top of config/routes.js that should do the trick: // config/routes.js '/*': function(req, res, next) {sails.log.verbose(req.method, req.url); next();}
Maybe too late, but for future references about this, I'm using Sails 0.11 and you can config that in the middleware, in the config/http.js file Add this function (in fact it comes as an example) // Logs each request to the console requestLogger: function (req, res, next) { console.log("Requested :: ", req.method, req.url); return next(); }, And setup it on the order var: order: [ 'startRequestTimer', 'cookieParser', 'session', 'requestLogger', // Just here 'bodyParser', 'handleBodyParserError', 'compress', 'methodOverride', 'poweredBy', '$custom', 'router', 'www', 'favicon', '404', '500' ]
I forked the sails-hook-requestlogger module to write all the request logs (access logs) to file. sails-hook-requestlogger-file All you have to do is npm install sails-hook-requestlogger-file and you are good to go! Usage Just lift your app as normal and all your server requests will be logged, with useful information such as response-time, straight to your console. As a default it is activated in your dev environment but deactivated in production. Configuration By default, configuration lives in sails.config.requestloggerfile You can create config/requestlogger.js and override these defaults: Parameter Type Details format ((string)) Defines which logging format to use. Deaults to dev. logLocation ((string)) Defines where to log: console or file. Defaults to console. fileLocation ((string)) Location of file relative to project root (if file is specified in logLocation. This has no effect if console is specified in logLocation. inDevelopment ((boolean)) Whether or not to log requests in development environment. Defaults to true. inProduction ((boolean)) Whether or not to log requests in production environment Defaults to false. Example config/requestlogger.js file: module.exports.requestloggerfile = { //see: https://github.com/expressjs/morgan#predefined-formats for more formats format: ':remote-addr - [:date[clf]] ":method :url" :status :response-time ms ":user-agent"', logLocation: 'file', fileLocation: '/var/log/myapp/access.log', inDevelopment: true, inProduction: true }; Hope that it would help someone :)
I found this matched my needs - it uses the Morgan module for Express and hooks it all up for you: https://www.npmjs.com/package/sails-hook-requestlogger