NestJS/Express Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client - express

Sometimes my server (NestJS) crashed with the following stack:
node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (/home/workspace/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/workspace/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/workspace/node_modules/express/lib/response.js:267:15)
at ExpressAdapter.reply (/home/workspace/node_modules/#nestjs/platform-express/adapters/express-adapter.js:24:57)
at ExceptionsHandler.handleUnknownError (/home/workspace/node_modules/#nestjs/core/exceptions/base-exception-filter.js:33:24)
at ExceptionsHandler.catch (/home/workspace/node_modules/#nestjs/core/exceptions/base-exception-filter.js:17:25)
at ExceptionsHandler.next (/home/workspace/node_modules/#nestjs/core/exceptions/exceptions-handler.js:16:20)
at /home/workspace/node_modules/#nestjs/core/router/router-proxy.js:24:35
at Layer.handle_error (/home/workspace/node_modules/express/lib/router/layer.js:71:5)
at trim_prefix (/home/workspace/node_modules/express/lib/router/index.js:315:13)
at /home/workspace/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/workspace/node_modules/express/lib/router/index.js:335:12)
at next (/home/workspace/node_modules/express/lib/router/index.js:275:10)
at Layer.handle_error (/home/workspace/node_modules/express/lib/router/layer.js:67:12) {
code: 'ERR_HTTP_HEADERS_SENT'
}
I tried to fix it with few advices I saw on similar SO (like here or here) but it still happens.
Dependencies used:
"#nestjs/common": "^7.6.12",
"#nestjs/config": "^0.6.3",
"#nestjs/core": "^7.6.12",
"#nestjs/jwt": "^7.2.0",
"#nestjs/mongoose": "^7.2.3",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.6.12",
"#nestjs/platform-socket.io": "^7.6.12",
"#nestjs/platform-ws": "^7.6.12",
"#nestjs/schedule": "^0.4.3",
"#nestjs/websockets": "^7.6.12",
"#types/string-similarity": "^4.0.0",
"bcrypt": "^5.0.1",
"class-transformer": "^0.2.3",
"class-validator": "^0.11.1",
"dotenv": "^10.0.0",
"express-useragent": "^1.0.15",
"mongodb": "^3.5.5",
"mongoose": "^5.9.7",
"nanoid": "^3.1.12",
"nestjs-i18n": "^8.1.0",
"nestjs-stripe": "^0.4.1",
"nodemailer": "^6.4.6",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"passport-local": "^1.0.0",
"path": "^0.12.7",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.0",
"rxjs": "^6.5.3",
"string-similarity": "^4.0.4",
"stripe": "^8.39.0",
"typeorm": "^0.2.24"
The code that may be problematic:
AppController:
#Controller()
export class AppController {
#Get()
root(#Res() response): void {
return response.sendFile(path.resolve(__dirname+'/../gui/index.html'));
}
}
AppMiddleware:
#Injectable()
export class AppMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
const url = req.originalUrl;
if (url.indexOf('api') === 1) {
// it starts with /api --> continue with execution
return next();
} else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
// it has a file extension --> resolve the file
return res.sendFile(path.resolve(__dirname + `/../gui/${url}`), err => {
// Error: redirect to index.html
if (err) {
return res.sendFile(path.resolve(__dirname + '/../gui/index.html'));
}
});
} else {
// in all other cases, redirect to the index.html
return res.sendFile(path.resolve(__dirname + '/../gui/index.html'));
}
}
}
I also tried with no return:
#Injectable()
export class AppMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
const url = req.originalUrl;
if (url.indexOf('api') === 1) {
// it starts with /api --> continue with execution
next();
} else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
// it has a file extension --> resolve the file
res.sendFile(path.resolve(__dirname + `/../gui/${url}`), err => {
// Error: redirect to index.html
if (err) {
res.sendFile(path.resolve(__dirname + '/../gui/index.html'));
}
});
} else {
// in all other cases, redirect to the index.html
res.sendFile(path.resolve(__dirname + '/../gui/index.html'));
}
}
}

In your AppMiddleware:
return res.sendFile(path.resolve(__dirname + `/../gui/${url}`), err => {
// Error: redirect to index.html
if (err) {
return res.sendFile(path.resolve(__dirname + '/../gui/index.html'));
}
});
This might be the cause. Your response ended after sendFile even when there would be an error, so you shouldn't invoke it in the callback.

Related

React native dependency of dependency requires pod dependency - new NativeEventEmitter requires a non-null argument

I have created a custom react-native package using react-native-builder-bob.
The package uses react-native-shake as a dependency.
My custom-package package.json:
"peerDependencies": {
"react": "*",
"react-native": "*",
"react-native-shake": "*"
},
"devDependencies": {
"react": "17.0.2",
"react-native": "0.67.2",
"react-native-builder-bob": "^0.18.0",
"react-native-shake": "^5.1.1"
}
When I start my custom-package everything works fine.
The custom-package uses RNshake as followed"
import RNShake from 'react-native-shake';
const MyFunction = () => {
useEffect(() => {
RNShake.addListener(() => {
//do something
});
});
return <></>
}
When installing the package on an app (using yalc) after starting the app I'm getting this error:
"new NativeEventEmitter(); requires a non-null argument"
what am i doing wrong here ?

Unable to sync RxDB with couchdb on react-native after creating collections

Why would rxdb throw this error when try to connect/sync on couch server Error Sync: TypeError: undefined is not an object (evaluating 'db.todos.syncCouchDB')
I tested the same function on my web app and works perfectly.
By the way I'm using it on android physical device and an iOS emulator.
try {
//syncing...
db.todos.syncCouchDB({
remote: 'http://admin:somepassword#127.0.0.1:5984/itony_todo_app',
options: {
live: true,
retry: true,
},
});
} catch (error) {
console.log(`Error Sync: ${error}`);
throw error;
}
My whole database init file is as follows:
import {createRxDatabase} from 'rxdb';
import {addPouchPlugin, getRxStoragePouch} from 'rxdb/plugins/pouchdb';
import SQLite from 'react-native-sqlite-2';
import SQLiteAdapterFactory from 'pouchdb-adapter-react-native-sqlite';
import {RxTodoDatabase, todoSchema} from './src/schema/todo';
const SQLiteAdapter = SQLiteAdapterFactory(SQLite);
addPouchPlugin(SQLiteAdapter);
addPouchPlugin(require('pouchdb-adapter-http'));
async function _create(): Promise<RxTodoDatabase> {
let db;
try {
console.log(`Creating Database`);
db = await createRxDatabase<RxTodoDatabase>({
name: 'itony_todo_app',
storage: getRxStoragePouch('react-native-sqlite'),
password: 'mystupidlongpassword',
multiInstance: false,
ignoreDuplicate: true,
});
} catch (err) {
console.log(`Error Creating database: ${err}`);
throw err;
}
try {
//adding collections
console.log('adding collections');
(await db).addCollections({
todos: {
schema: todoSchema,
},
});
} catch (error) {
console.log(`Error adding collections: ${error}`);
throw error;
}
try {
//syncing...
db.todos.syncCouchDB({
remote: 'http://admin:213580#127.0.0.1:5984/itony_todo_app',
options: {
live: true,
retry: true,
},
});
} catch (error) {
console.log(`Error Sync: ${error}`);
throw error;
}
console.log('Database initiated...');
return db;
}
const DatabaseService = {
DB_CREATE_PROMISE: _create(),
get(): Promise<RxTodoDatabase> {
return this.DB_CREATE_PROMISE;
},
};
export default DatabaseService;
my package.json is as follows maybe I'm missing something, I don't know, maybe there's a certain package missing...
"dependencies": {
"base-64": "^1.0.0",
"events": "^3.3.0",
"pouchdb-adapter-http": "^7.2.2",
"pouchdb-adapter-react-native-sqlite": "^3.0.1",
"react": "17.0.2",
"react-native": "0.68.0",
"react-native-get-random-values": "^1.7.2",
"react-native-sqlite-2": "^3.5.2",
"rxdb": "^11.6.0",
"rxjs": "^7.5.5",
"uuid": "^8.3.2"
}
It's likely a race condition with async functions, addCollections isn't awaited.
Try replacing (await db).addCollections with await db.addCollections, like this:
try {
//adding collections
console.log('adding collections');
await db.addCollections({
todos: {
schema: todoSchema,
},
});
} catch (error) {
console.log(`Error adding collections: ${error}`);
throw error;
}

Error deploying smart contract using Hardhat -- Error HH9: Error while loading Hardhat's configuration

Trying to deploy a smart contract using Hardhat but getting configuration error.
Here is the complete error details
Error HH9: Error while loading Hardhat's configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it.
This is not possible, as Hardhat can't be initialized while its config is being defined.
All the plug-ins seem to be have been installed correctly.
deploy.js
const hre = require("hardhat");
async function main() {
const TestContract = await hre.ethers.getContractFactory("TestContract");
const superInstance = await TestContract.deploy("TestContractHAT", "SMC");
await superInstance.deployed();
console.log("contract was deployed to:", superInstance.address());
}
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "Test",
"version": "1.0.0",
"description": "This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, a sample script that deploys that contract, and an example of a task implementation, which simply lists the available accounts.",
"main": "hardhat.config.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.5",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.2"
},
"dependencies": {
"dotenv": "^16.0.0",
"hardhat": "^2.9.3"
}
}
Hardhat.config
const { ethers } = require("hardhat");
require('#nomiclabs/hardhat-waffle');
require("#nomiclabs/hardhat-ethers");
require('#openzeppelin/hardhat-upgrades');
require("dotenv").config();
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.2",
networks: {
mumbai: {
url: process.env.MUMBAI_URL,
account: process.env.PRIVATE_KEY
}
}
};
Any pointers are helpful. Thanks
As the error states, you are importing hardhat module in your hardhat configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it. This is not possible, as Hardhat can't be initialized while its config is being defined.
Remove the line
const { ethers } = require("hardhat");
and the error should disappear
Just remove
const { ethers } = require("hardhat");
or
const { hardhatArguments } = require("hardhat");
or any other that requires hardhat

undefined is not an object (evaluating '_effects.buffers.expanding')

I'm getting an error when tried to copy&paste this solution in my app.
undefined is not an object (evaluating 'effects.buffers.expanding')
My code is pretty similar:
export function* handleBleState() {
const {
bleConnections: { manager },
} = yield select()
const stateChannel = yield eventChannel((emit) => {
const subscription = manager.onStateChange((state) => {
emit(state)
}, true)
return () => {
subscription.remove()
}
}, buffers.expanding(1))
try {
for (;;) {
const newState = yield take(stateChannel)
const power = newState === 'PoweredOn'
yield put(BLEActions.updateBleState(power))
}
} finally {
if (yield cancelled()) {
stateChannel.close()
}
}
}
But what is more strange is that I have extracted code from the documentation of redux-saga and the error is similar.
I replaced part of the code with this:
const stateChannel = yield eventChannel((emitter) => {
const iv = setInterval(() => {
secs -= 1
if (secs > 0) {
emitter(secs)
} else {
// this causes the channel to close
emitter(END)
}
}, 1000)
// The subscriber must return an unsubscribe function
return () => {
clearInterval(iv)
}
})
And I get:
undefined is not a function (evaluating '(0, _effects.eventChannel)')
I'm using another version of redux-saga:
"redux-saga": "^1.0.2",
But I tried with the same version that he use
"redux-saga": "0.16.2"
And then the issue is another one:
console.error: "unchaught at root", "at root at takeLatest" at handleBleState etc, etc.
Any help will be welcome, thanks in advance.
PD:
"react": "16.6.1",
"react-native": "0.57.5",
"react-native-ble-plx": "^1.0.1",
the eventChannel is nor part of the effects but defined directly in the main module, see the relevant API doc. So if you're using ES6 import/export you import it with the following statement:
import { eventChannel } from 'redux-saga'
While the require equivalent should be:
const eventChannel = require('redux-saga').eventChannel

React Native - Exception '-[NSNull length]: unrecognized selector sent to instance 0x1e6c059b0' was thrown while invoking multiSet on

I get this error few seconds after the app is loaded (but not always sometimes after few minutes or few downloads). I need to solve this issue.
if more details are needed and/or editing - please tell me and I'll make them.
Exception '-[NSNull length]: unrecognized selector sent to instance 0x1e6c059b0' was thrown while invoking multiSet on target AsyncLocalStorage with params (
(
(
"#Ye-Music:songs",
""
)
),
483
)
The function with AsyncStorage:
allSongs = () => {
console.log('hello function!');
fetch(URL + "/SongsList", {
body: null, //// sending null because its a view from SQL db
method: "POST",
headers: {
Accept: 'application/json',
"Content-type": "application/json; charset=UTF-8"
}
})
.then(res => { return res.json()})
.then((songsResult) => {
AsyncStorage.setItem("#Ye-Music:songs", songsResult.d);
})
.catch(err => {
console.error(err);
});
};
package.json
"dependencies": {
"#expo/samples": "2.1.1",
"expo": "29.0.0",
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-29.0.0.tar.gz",
"react-native-elements": "^0.19.1",
"react-native-material-cards": "^1.0.9",
"react-native-music-control": "^0.7.3",
"react-native-music-player-service": "^0.1.4-beta",
"react-native-search-header": "^0.3.0",
"react-native-sound": "^0.10.9",
"react-native-track-player": "^0.2.5",
"react-navigation": "^2.9.3"
},
When calling AsyncStorage, the value needs to be defined. If it's not, you'll get the error you encountered.
Error handling logic (for the undefined case) is probably the best way to go.
if(songsResult && songsResult.d) {
AsyncStorage.setItem("#Ye-Music:songs", songsResult.d);
} else {
// handle error case here
}
Make sure songsResult.d is not undefined and is a string with a length > 0 !