>PROBLEM
>SOLUTION
Create a revision summary.
Create a revision summary.
A request generates the following error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
It happens when some exception occurs before returning the request, for instance a "res.sent" statement.
Debug the application step-by-step.
To simplify, you may comment on the code from the start.
Tip: check database exceptions not treated.
Having more than one exception becomes tricky if you can't reproduce the same request.
Be sure to fix all possible exceptions.
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
Supposing using date-and-time lib:
npm install date-and-time --save
const date = require('date-and-time')
and the date returning the standard format, something like this (locale: Brazil):
obj.createdAt = 'Fri Aug 26 2022 21:14:34 GMT-0300 (Horário Padrão de Brasília)';
the compiler throws the following error:
date-and-time offset = dateObj.getTimezoneOffset()
TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')
created_at: date.format(obj.createdAt, 'YYYY/MM/DD HH:mm:ss'),
created_at: date.format(new Date(obj.createdAt), 'YYYY/MM/DD HH:mm:ss'),
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
TypeError: Cannot read properties of undefined
This error may have many causes.
Here, it's shown a tricky one — cyclic reference, when one file references the other.
Check the example below:
const UserSvc = require('../../models/business/UserSvc');
static verifySToken(req) {
if (req === 'undefined' || req == null) return false;
let userStoken = UserSvc.stokenSvc[req.body.email];
//...
}
const SecTools = require('../security/SecTools');
myOtherfunction() {
user.token = SecTools.signWithJwt(user.email);
}
The SecTools has reference to UserSvc, and vice-e-versa.
Remove the cyclic reference to fix the issue.
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
Express returns compilation error:
node:internal/modules/cjs/loader:488
throw e;
^
node:internal/modules/cjs/loader:488 throw e; ^ Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\ express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'
at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15) at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15) at resolveExports (node:internal/modules/cjs/loader:482:14) at Function.Module._findPath (node:internal/modules/cjs/loader:522:31) at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (M:\work\devcli_\javascript\jstopics\ express\node_sequelize_ultering_ml40643\prj\models\security\SecTools.js:5:19) at Module._compile (node:internal/modules/cjs/loader:1101:14) { code: 'MODULE_NOT_FOUND', path: 'M:\\work\\devcli_\\javascript\\jstopics\\ express\\node_sequelize_ultering_ml40643\\prj\\node_modules\\sequelize\\package.json' }
Attempt to send email fails returning the following message:
javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at
Configuration used:
PROPS.put("mail.debug", "false");
PROPS.put("mail.smtp.port", "587");
PROPS.put("mail.smtp.auth", "true");
PROPS.put("mail.smtp.starttls.enable", "true");
PROPS.put("mail.smtp.host", "smtp.googlemail.com");
PROPS.put("mail.smtp.ssl.trust", "smtp.gmail.com");
PROPS.put("mail.smtp.ssl.protocols", "TLSv1.2");
PROPS.put("mail.smtp.host", "smtp.gmail.com");
session = Session.getInstance(PROPS, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SENDER, PASSWORD);
}
});
After installing MongoDB libs
npm i --save mongoose
npm install @types/mongoose --save-dev
-- used for MongoClient
npm install --save mongodb
npm install --save dotenv
Warning: Module not found: Error: Can't resolve
./node_modules/mongodb/lib/bson.js:12:9-28 - Warning: Module not found: Error: Can't resolve 'bson-ext' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'
./node_modules/mongodb/lib/deps.js:36:2-40 - Warning: Module not found: Error: Can't resolve 'kerberos' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'
./node_modules/mongodb/lib/deps.js:43:2-49 - Warning: Module not found: Error: Can't resolve '@mongodb-js/zstd' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'
./node_modules/mongodb/lib/deps.js:51:2-36 - Warning: Module not found: Error: Can't resolve 'snappy' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'
./node_modules/mongodb/lib/deps.js:54:75-105 - Warning: Module not found: Error: Can't resolve 'snappy/package.json' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'
./node_modules/mongodb/lib/utils.js:1399:32-87 - Warning: Critical dependency: the request of a dependency is an expression
./node_modules/mongodb/lib/utils.js:1407:32-68 - Warning: Module not found: Error: Can't resolve 'mongodb-client-encryption' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'
Sometimes, we are not sure if the environment is consistent or not.
The issue reported here was caused by the last lib installed (mongodb) in the app's env.
If you want to check this, you may skip steps and go straight to the fourth approach topic, at the end.
If you do want to recheck your app's env, you may start from the 1st approach.
First of all, stop the application, and close the IDE (VSCode/Eclipse, etc.).
- try:
npm cach verify
Retest.
If the 1st step didn't work, try to unistall the last libs installed.
In this case, it was the following:
npm uninstall mongoose
npm uninstall @types/mongoose
npm uninstall mongodb
npm uninstall dotenv
- do:
npm cach clean
or
npm cach clean --force
- reinstall them:
npm i --save mongoose
npm install @types/mongoose --save-dev
npm install --save mongodb
npm install --save dotenv
- do:
npm install
- restart the app.
If the 2nd step didn't work, remove all cache and node_modules, reinstalling the libs.
- alternatively install:
npm install node-gyp -g
- run:
npm cache clean --force
rm -Rf node_modules
npm install
npm cache verify
- restart the app.
If the 3rd step didn't work, probably it is some lib issue.
To discover the cause, the libs were tested one at a time.
To discover the cause, test the libs one at a time.
Making rollback, both libs were uninstalled.
The it was reinstalled mongoose and tested with minimal code.
Passed.
Then, it was installed MongoClient and tested with minimal code.
The issue returned.
To discover the cause, the code was commented and tested one statement at a time, restarting the app.
First:
import * as mongoDB from 'mongodb';
import * as dotenv from 'dotenv';
After, code was commented and the cause was this line:
const client = new mongoDB.MongoClient('mongodb://localhost:27017/test');
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
Using typscript and TSLint, return the following message:
expected call-signature: 'run1' to have a typedef
async run1() {
await mongoose.connect('mongodb://127.0.0.1');
}
async run1(): Promise<any> {
await mongoose.connect('mongodb://127.0.0.1');
}
VSCode
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
Attempt to access the site returns the following error messages:
- On browser console:
crbug/1173575, non-JS module files deprecated.
- On browser page:
ERR_SSL_PROTOCOL_ERROR
Não foi possível estabelecer uma conexão segura com este site
Not possible to establish a secure connection with the site
Probably you've tried to access the site using https where it should be http.
Ex.:
- wrong:
https://localhost:3000
- because it uses the http protocol service, so:
http://localhost:3000
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
The compilation returns the follwing warning message:
Warning: There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
Two things to check:
1. If working on Windows, files hasn't case sensitive approach.
So, make sure that the file pointed by the warning message matches case.
If not, remember that it doesn't help renaming the file. It is necessary to rename the file to a different one and then rename it back using the name with the right case.
2. Check the import referred by the error message that it is pointing to the path with different case.
It works on Windows but not on *nix or Mac.
Follow by the images.
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
An element is not recognized, returning the following error message:
angular: is not a known element
The issue is caused by a missing reference that becomes invalid.
It is example happened because the component was deleted using the editor, but it was not able to remove the respective reference together.
It may happen also when you rename or move componets.
Removing the missing references:
the problem is gone.
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
When angular compiles, returns the following error:
Error: src/app/crud/crud-employee/crud-employee-list/crud-employee-list.component.html:28:11 - error NG8001: 'pagination-controls' is not a known element:
1. If 'pagination-controls' is an Angular component, then verify that it is part of this module.
2. If 'pagination-controls' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
28 <pagination-controls id="employees_listing_pagination" maxSize="5" directionLinks="true" (pageChange)="page = $event"></pagination-controls>
This kind of error message happened when using ngx-bootstrap and some other kind of issue promotes a compilation errors returning eventually this message.
The most common issues were:
1. Malformed module configuration.
2. Non-visible chars resulting in unexpected combinations.
3. Components not declared.
Mysterious compilation errors suddenly appeared after restarting app.
It may happen with any framework/language.
Context:
Everything was done right and the modifications implemented were compiled successfully. Suddenly, after restarting the app, many error messages come from nowhere and they seem not compatible with the code written.
When the compilation goes mad, indicates that something outside the project, pertaining to the O.S. system has come to the scene.
Most common causes that occurred to me:
- HD issue
- Corrupted files.
- Non-visible chars (the worst scenario) resulting in unexpected combinations..
The first two causes may be easier to find out.
The third may turn your search into hell.
Through the editor used during the project implementation may not help, because the issue in this cases usually comes transparent to it. For instance, if you are using VS Code (excellent), it will be necessary to use another one to identify the issue, for instance the Notepad++, SciTE, or another one.
In the image below, check the red arrow.
The strange char comes out.
It doesn't help correcting in the editor. The issue may persist because it may have not visible chars during the fix, and they will be still there and may cause more issues.
The best thing to do is to create a new file and retype the code.
You may risk doing just this with just the defective line.
Better if you replace all the code from another source or manually.
Windows
Node.js
Angular 12 and higher.
Angular compilation throws the following error:
Error: node_modules/ngx-bootstrap/modal/bs-modal.service.d.ts:7:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.
This likely means that the library (ngx-bootstrap/modal) which declares BsModalService has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.
imports: [
BsModalService,
],
providers: [
],
imports: [
BsModalService,
],
providers: [
BsModalService,
],
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
Angular compilation returns:
Error: node_modules/ngx-bootstrap/datepicker/bs-datepicker.config.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.
This likely means that the library (ngx-bootstrap/datepicker) which declares BsDatepickerConfig has not been processed correctly by ngcc, or is not compatible with Angular Ivy.
Check if a newer version of the library is available, and update if so.
Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.
Edit app.module.ts and fix its configuration as follows:
imports: [
AlertConfig,
BsDropdownConfig,
BsDatepickerConfig
],
providers: [],
imports: [
],
providers: [AlertConfig, BsDropdownConfig, BsDatepickerConfig],
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
After adding an implementation to bind using ngModel , for instance:
<label for="example-ngModel">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example-ngModel">
Running angular using ngModels, returns the error message:
error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'
Can't bind to 'formGroup' since it isn't a known property of 'form'
Error: src/app/crud/crud-employee/crud-employee-update/crud-employee-update.component.html:2:9 - error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.
2 <form [formGroup]="updateForm" (ngSubmit)="saveToList(updateForm)">
For instance, implementing a simple example like this:
You get:
Set the required modules in app.modules.ts. Example:
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
...
@NgModule({
declarations: [
//...
],
imports: [
//...
FormsModule,
ReactiveFormsModule,
],
*** IMPORTANT NOTE:
If you are using a page under its specific module, declare in that module too.
Example:
app
+--forms-lab
+-- forms1
--- forms-lab.module.ts
Edit forms-lab.module.ts and declare both modules referred to above.
It is something easy to happen, for instance, if you create a module called forms, as it is:
ng g m forms
This command will generate a FormsModule that overrides the angular's module.
This conflict causes the same issue.
If it happened, delete, and recreate it with another name.
Using the example above, it would be something like this in the forms-lab.module.ts file:
Sometimes, the way the components are named may cause the issue.
Check the following image:
@MORE:
Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64
node.js: express: req.session returns "undefined".
console.log(req.session)
- Returns:
undefined
The session block declaration shall come before the routing blocks.
Scenario by example:
On a linux(debian, ubuntu, etc) system you want to discover the postgresql service, its version and how to stop/start.
1. whereis
2. locate
3. ps aux
Ex.: ps aux | grep postgres
/usr/lib/postgresql/13/bin/postgres -D /var/lib/postgresql/13/main -c config_file=/etc/postgresql/13/main/postgresql.conf
4. systemctl
returns all registerd services
systemctl stop ssh
systemctl disable ssh
systemctl enable ssh
systemctl start ssh
systemctl status ssh
service postgresql status
service postgresql start
service postgresql stop
linux/debian
On Windows, after running a git command, it is thrown the following warning:
hint: core.useBuiltinFSMonitor will be deprecated soon; use core.fsmonitor instead
hint: Disable this message with "git config advice.useCoreFSMonitorConfig false"
core.fsmonitor
If set to true, enable the built-in file system monitor daemon for this working directory (git-fsmonitor--daemon[1]).
Like hook-based file system monitors, the built-in file system monitor can speed up Git commands that need to refresh the Git index
(e.g. git status) in a working directory with many files.
The built-in monitor eliminates the need to install and maintain an external third-party tool.
- Documentation:
https://git-scm.com/docs/git-config#Documentation/git-config.txt-corefsmonitor
Run the desired option:
git config core.fsmonitor true
or
git config core.fsmonitor false
*** IMPORTANT NOTE:
Run the command on the git's root folder.
Make sure that the git folder is not another git subdirectory of a root git folder.
Example:
+-- project
.git
myStuff
+-- project2
.git
myStuff2
git version 2.36.0.windows.1
Windows 10
Attempt to run an Eclipse project returns the following error:
Error: Could not find or load main class antlr.debug.misc.ASTFrame
Caused by: java.lang.ClassNotFoundException: antlr.debug.misc.ASTFrame
0. Pre-requisite: make sure your pom.xml configuration is correct.
1. On Eclipse, using the Project Explorer (or Navigator), delete the following configuration files:
.settings
.classpath
2. Eclipse will complaing throwing an error pop-up. Ignore closing it.
3. Using the Project Explorer (or Navigator), point to the project's root and save it again.
This will generate again the deleted files.
4. Check if there are errors and fix them.
maven
eclipse
java17
The pom.xml shows the following error message:
Execution default-testResources of goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:testResources failed: Unable to load the mojo 'testResources'
(or one of its required components) from the plugin 'org.apache.maven.plugins:maven-resources-plugin:3.2.0'
(org.apache.maven.plugins:maven-resources-plugin:3.2.0:testResources:default-testResources:process-test-resources)
If the pom.xml was previously working fine, just update the maven project.
If using Eclipse, do:
Point to the project root on "Project Explorer" or equivalent, choose on the context menu mave, Updata Project (or ALT+F5)
spring
java
Running the executable jar with dependencies generated by maven plugin fails throwing the error message:
java -jar myApp-0.0.1-SNAPSHOT-jar-with-dependencies.jar
- Returns:
..Caused by: java.lang.ClassNotFoundException..
1. Check the main class path in the pom.xml file.
Note: there are alternative plugins to generate executable jars.
See more at:
How to Create an Executable JAR with Maven
Below is shown one of the options:
Starting a project using Maven, JEE/Spring, and MongoDB driver (mongo-java-driver) throws the following exception:
...[cluster-ClusterId{value='62586e27f362ec2cd1336bda', description='null'}-localhost:27027] # INFO # org.mongodb.driver.cluster # method: info # Exception in monitor thread while connecting to server localhost:27027
com.mongodb.MongoSocketOpenException: Exception opening socket
...
Caused by: java.net.ConnectException: Connection refused: no further information at java.base/sun.nio.ch.Net.pollConnect(Native Method)
Although connection refusal may have many causes, this post will treat one of them that maybe it is your issue.
The "mongo-java-driver" tries to start MongoDB connection automatically as soon as the application starts if it finds MongoDB's configuration in .properties or .yml files.
It happens when we start a project using this default feature but later we decide to customize it, and there is no need for this feature anymore.
So, just remove or comment on the lines in the configuration file.
For instance, if .yml, do this:
spring:
profiles: prod
jpa:
database: default
# data:
# mongodb:
# host: localhost
# port: 27027
# database: mydatabase
If .properties:
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=mydatabase
SpriingBoot 2.X
Java 17
MongoDB 5
- pom.xml:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.10</version>
</dependency>
>PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...