ReferenceError: config is not defined - Node Login Authentication - javascript

I am new to nodejs and I am follow this link for a simple login authentication but however as I am trying to follow up process I have configured a local mongodb database and as per the instructions I have updated the database.js file like -->
config/database.js
module.exports = {
'mongodb': '//localhost/loginApp'
};
but however when I try to run
node server.js
I am getting error as follows
can Someone help ?! I cant understand what is the issue with it ?!

Looks like that you have this config/database.js in line 1 in your database.js file.
This should be commented out like //config/database.js. So Your code should be like
//config/database.js
module.exports = {
'mongodb': '//localhost/loginApp'
};

Related

next.js environment variables are undefined (Next.js 10.0.5)

I am coding a website with Next.js and I tried to add google Tag Manager.
I followed the tutorial on the Next.js Github example but for some reasons I can't access to my environment variables.
It says my variable is undefined.
I created a file .env.local on my project folder (at the same level as components, node_modules, pages, etc)
In this file I created a variable like this (test purpose) :
NEXT_PUBLIC_DB_HOST=localhost
And on my index page I tried this code :
console.log("test ", process.env.NEXT_PUBLIC_DB_HOST);
But in my console I get a "test undefined".
I tried to put my variable into an .env file instead, without success.
What I am doing wrong ?
This envs just works in Server Side. To access this envs in Client Side, you need declare in the next.config.js
This way:
module.exports = {
reactStrictMode: true,
env: {
BASE_URL: process.env.BASE_URL,
}
}
Create .env (all environments), .env.development (development environment), and .env.production (production environment).
Add the prefix NEXT_PUBLIC to all of your environment variables.
NEXT_PUBLIC_API_URL=http://localhost:3000/
Use with prefix process.env
process.env.NEXT_PUBLIC_API_URL
Stop the server and restart it:
npm run dev
I hope it works.
This solution for latest version of nextJs (above 9)
Restarting the server worked for me.
Edit & save .env.local
Stop the server and restart it, npm run dev
You should get an output on the next line like this:
> klout#0.1.0 dev
> next dev
Loaded env from [path]/.env.local
For those using NextJS +9 and looking for environment variables in the browser, you should use the NEXT_PUBLIC_ prefix. Example:
NEXT_PUBLIC_ANALYTICS_ID=123456789
See documentation for reference.
After spending countless hours on this, I found that there is a tiny little paragraph in both the pre and post nextjs 9.4 documentation:
(Pre-9.4) https://nextjs.org/docs/api-reference/next.config.js/environment-variables (same as this answer)
Next.js will replace process.env.customKey with 'my-value' at build time.
(^9.4) https://nextjs.org/docs/basic-features/environment-variables
In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time.
Key words being BUILD TIME. This means you must have set these variables when running next build and not (just) at next start to be available for the client side to access these variables.
This is my next.config.js file.
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
env: {
BASE_URL: process.env.NEXT_PUBLIC_SITE_URL,
},
};
module.exports = nextConfig;
Restart the server and it worked fine. using Nextjs 12.1.0 with typescript
In my case, Im pasting REACT_APP_API_URL instead of NEXT_PUBLIC_API_URL.
Adding with the most recent version of the documentation on this, v12+.
Using the next.config.js file you can specify server and client variables:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
You can still use an env.local file, and pass the variable in to the next.config.js file. For example:
publicRuntimeConfig: {
DB_URL: process.env.DB_URL
}
And then you can access the variable like this:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
publicRuntimeConfig.DB_URL;

Jest TypeError: Document.save is not a function

I'm trying to write some tests for an Express app where I have an User model. One of my methods looks like this:
let user = await User.findById(req.params.userId);
user.name = req.body.name || user.name;
user.password = req.body.password || user.
user = await user.save();
The code runs as it should, but when I test it, Jest complains:
TypeError: user.save is not a function
Right now I'm mocking my whole User model like this:
jest.mock('../../models/User');
I tried to mock the save function like this, but nothing changed:
jest.spyOn(User.prototype, 'save')
.mockImplementationOnce(() => Promise.reject('fail update'))
As I said before, the code runs fine. I don't get this error when I run the server.
However, there is one weird thing happening: when I run the tests I get this warning from mongoose
Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: http://mongoosejs.com/docs/jest.html
I read the docs and what it said was to set testEnvironment as 'node' on Jest config file, which I'm already doing. This is my jest.config.js file:
module.exports = {
testEnvironment: 'node'
};
However I keep getting the warning.
This is my test script:
jest --watchAll
Any help will be appreaciated. Thanks in advance
The reason why you are receiving that error is this line:
let user = User.findById(req.params.userId)
findById() is an asynchronous method, so you have to put the await keyword in the code, like this:
let user = await User.findById(req.params.userId)
As your code is not really awaiting a response from findById() that user variable is undefined hence user.save() indeed is not a function. You could try to print console.log(user), and it'll be undefined.
To avoid this message "Mongoose: looks like you're trying to test a Mongoose app with Jest's..." you have to configure Jest in your package.json, like this:
"jest": {
"testEnvironment": "node"
},

Dashing-JS "Hello World" Demo

I am attempting to work with Dashing-JS, a port of a Sinatra based framework project in Ruby, Dashing.IO, to Javascript/Node. Essentially I have the core packages and dependencies for Dashing-JS configured; however, when attempting to run just the sample, I am unable to display anything other than this 404 error rather than a sample dashboard:
NodeJS CLI output is as follows:
The project is not well maintained; however, I am curious if an expert in Node might be able to shed some light on the situation. Is a path reference incorrect?
Notes:
1. server.js is referencing sample.jade.
var dashing = require('new-dashing-js').Dashing();
// Set your auth token here
//dashing.auth_token = 'YOUR_AUTH_TOKEN';
/*
dashing.protected = function(req, res, next) {
// Put any authentication code you want in here.
// This method is run before accessing any resource.
// if (true) next();
}
*/
// Set your default dashboard here
dashing.default_dashboard = 'sample';
dashing.start();
"Sample.jade" is located within the "dashboards" directory

Loggly: Unable to receive logs from NodeJs with Winston

I configured everything regarding the documentation's page.
I get no error from my Node app, however I don't receive any log on loggy from my app.
I can't figure out where does the problem come from.
My code in config.js:
var winston = require('winston');
require('winston-loggly-bulk');
winston.add(winston.transports.Loggly, {
inputToken: "aToken",
subdomain: "aSubDomain",
tags: ["Winston-NodeJS"],
json:true
});
winston.log('info',"Hello World from Node.js!");
Your config looks fine. Did you check you are using the right token from https://YourSubdomain.loggly.com/tokens not from https://YourSubdomain.loggly.com/account/users/api/tokens? The use of both the tokens are different so this could be a reason that you are not seeing any log in your account.

AWS Lambda Function is returning "Cannot find module 'index'" yet the handler in the config is set to index

As my title explains I am getting the following error:
{
"errorMessage": "Cannot find module 'index'",
"errorType": "Error",
"stackTrace": [
"Function.Module._resolveFilename (module.js:338:15)",
"Function.Module._load (module.js:280:25)",
"Module.require (module.js:364:17)",
"require (module.js:380:17)"
]
}
I have tried both solutions provided in creating-a-lambda-function-in-aws-from-zip-file and simple-node-js-example-in-aws-lambda
My config currently looks like:
and my file structure is:
and my index.js handler function looks like :
exports.handler = function(event, context) {
What else could be causing this issue aside from what was stated in those two answers above? I have tried both solutions and I have also allocated more memory to the function just incase thats why it couldn't run.
EDIT -
For the sake of trying, I created an even simpler version of my original code and it looked like this:
var Q = require('q');
var AWS = require('aws-sdk');
var validate = require('lambduh-validate');
var Lambda = new AWS.Lambda();
var S3 = new AWS.S3();
theHandler = function (event, context) {
console.log =('nothing');
}
exports.handler = theHandler();
And yet still does not work with the same error?
Try zipping and uploading the contents of the folder lambda-create-timelapse. Not the folder itself.
If this was unclear for anyone else, here are the steps:
Step 1
Navigate to the folder of your project, and open that folder so that you are inside the folder:
Step 2
Select all of the images you want to upload into to Lambda:
Step 3
Right-click and compress the files you have selected:
This will give you a .zip file, which is the file you need to upload to Lambda:
There are a lot of ways to automate this, but this is the manual procedure.
I ran into this problem a few times myself, and this indeed has to do with zipping the folder instead of just the contents like you're supposed to.
For those working from the terminal...
While INSIDE of the directory where the .js files are sitting, run the following:
zip -r ../zipname.zip *
The * is instructing the client to zip all the contents within this folder, ../zipname.zip is telling it to name the file zipname.zip and place it right outside of this current directory.
I had the same problem sometime ago - I reformatted the code.
function lambdafunc1(event, context) {
...
...
...
}
exports.handler = lambdafunc1
The problem occurs when the handler cannot be located in the zip at first level. So anytime you see such error make sure that the file is at the first level in the exploded folder.
To fix this zip the files and not the folder that has the files.
Correct Lambda function declaration can look like this:
var func = function(event, context) {
...
};
exports.handler = func;
You may have other syntax errors that prevent the index.js file from being properly ran. Try running your code locally using another file and using the index.js as your own module.
make sure in your handler following code added
exports.handler = (event, context, callback) => {
...
}
Another reason this can occur is if you don't do an npm install in the folder before packaging and deploying.

Categories