Search This Blog

Showing posts with label Troubleshoot. Show all posts
Showing posts with label Troubleshoot. Show all posts

Wednesday, January 15, 2025

How to post request in node js using http-proxy-middleware

 

Recently we faced issue to post the request via api server to another server to fix follow the 

code as below:

In node app.js use following to proxy post request to different server:

const postProxy = createProxyMiddleware({

target: 'http://localhost:4000/', // Target server
changeOrigin: true, // Change the origin header to the target URL
pathRewrite: {
'^/api': '', // Remove /api from the path when forwarding
},
on: {
proxyReq: fixRequestBody
},
onProxyReq: (proxyReq, req, res) => {
// Forward request body for POST requests
if (req.body && Object.keys(req.body).length > 0) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
console.log(proxyReq);
}
},
logLevel: 'debug', // Enable detailed logs
});
// Proxy POST requests to /api/*
app.use(
'/api', postProxy
);


Cheers

Happy Coding !!

Thursday, January 9, 2025

How to handle cors error in node js


     CORS (Cross-Origin Resource Sharing) errors occur when a browser blocks a request made to a server that is on a different origin (domain, protocol, or port) than the client making the request. 

    To handle CORS errors in a Node.js application, you need to configure the server to explicitly allow cross-origin requests.

Following are Steps to Handle CORS in Node.js:


1. Use the cors Package

The easiest way to handle CORS in Node.js is by using the popular cors middleware package.

Install the cors Package:
bash

npm install cors
Example Usage in Your App:
const express = require('express'); const cors = require('cors'); const app = express(); // Allow CORS for all origins app.use(cors()); // Optional: Allow specific origins or methods const corsOptions = { origin: 'http://example.com', // Replace with your frontend's origin methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allowed HTTP methods allowedHeaders: ['Content-Type', 'Authorization'], // Allowed headers }; app.use(cors(corsOptions)); app.get('/api/data', (req, res) => { res.json({ message: 'CORS is working!' }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });

2. Manually Set CORS Headers

If you don't want to use the cors package, you can manually set CORS headers in your responses.

Example:
const express = require('express'); const app = express(); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); // Allow all origins res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // Handle preflight requests (OPTIONS method) if (req.method === 'OPTIONS') { return res.status(204).end(); } next(); }); app.get('/api/data', (req, res) => { res.json({ message: 'CORS headers set manually!' }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });

3. Debugging CORS Issues

If you are still encountering CORS issues:

  • Check the Origin Header: Ensure that the client's request includes the correct Origin header.
  • Check Preflight Requests: For PUT, DELETE, and other methods, browsers send a preflight OPTIONS request to check permissions. Ensure your server handles this method.
  • Check Browser Console: The error messages in the console often provide hints about what is misconfigured.
  • Check API Proxy Settings: If you're using a proxy (e.g., in Angular, React, or Vue), ensure the proxy is properly routing requests.

4. For Development Environments

If you're testing locally and don't want to configure strict CORS rules, you can allow all origins temporarily:

app.use(cors({ origin: '*' }));

5. For Production

For production environments, always restrict access to trusted origins:


const corsOptions = { origin: ['https://trusted-frontend.com', 'https://another-trusted-site.com'], // List of trusted origins methods: ['GET', 'POST'], allowedHeaders: ['Content-Type', 'Authorization'], }; app.use(cors(corsOptions));

This approach ensures that your API complies with security requirements while avoiding CORS errors in browsers.

Friday, January 3, 2025

How to Prevent the "Cannot Read Property 'map' of Undefined" Error

  

    One of the most common errors encountered by JavaScript developers, especially when working with arrays and React, is the infamous:

TypeError: Cannot read property 'map' of undefined

This error indicates that the code is trying to call the map method on a value that is undefined. Here, we’ll break down the causes of this error and provide actionable solutions to prevent it.


Understanding the Problem

The map method is used to iterate over an array and transform its elements. If the value you’re trying to call map on isn’t an array (e.g., undefined, null, or another non-array type), JavaScript will throw this error.

Common Scenarios

  1. Undefined or null data:

    const items = undefined;
    items.map(item => console.log(item)); // TypeError
  2. Asynchronous data loading: When fetching data from an API, the array might not be available immediately.

    const [data, setData] = useState();
    useEffect(() => {
        fetch('/api/data')
            .then(response => response.json())
            .then(fetchedData => setData(fetchedData));
    }, []);
    
    data.map(item => console.log(item)); // TypeError
  3. Incorrect initial value: You might set the state to undefined or forget to initialize it as an empty array.


Strategies to Prevent the Error

1. Initialize Variables Properly

Always initialize variables that will hold arrays with an empty array. This ensures the map method can be safely called.

const items = [];
items.map(item => console.log(item)); // Safe, no error

2. Use Optional Chaining

Optional chaining (?.) prevents accessing properties or methods on undefined or null.

items?.map(item => console.log(item)); // No error, but does nothing if items is undefined

3. Provide Default Values

Using default parameters or the || operator ensures a fallback array if the value is undefined.

Example 1: Default Parameter

function processItems(items = []) {
    items.map(item => console.log(item));
}

Example 2: Logical OR

(items || []).map(item => console.log(item));

4. Check the Type Before Calling map

Explicitly validate the type of the variable to ensure it is an array.

if (Array.isArray(items)) {
    items.map(item => console.log(item));
} else {
    console.log('items is not an array');
}

5. Handle Asynchronous Data Gracefully

When working with APIs or asynchronous operations, make sure to handle the loading state properly.

const [data, setData] = useState([]); // Initialize with an empty array

useEffect(() => {
    fetch('/api/data')
        .then(response => response.json())
        .then(fetchedData => setData(fetchedData))
        .catch(error => console.error('Error fetching data:', error));
}, []);

return (
    <div>
        {data.map(item => (
            <p key={item.id}>{item.name}</p>
        ))}
    </div>
);

Debugging Tips

If you encounter this error, follow these steps to debug it:

  1. Log the Variable: Use console.log to check the value of the variable before calling map.

    console.log(items);
  2. Check Data Flow: Trace the origin of the variable to ensure it’s being set correctly.

  3. Handle Edge Cases: Consider scenarios where the variable might be undefined or null, especially when working with dynamic or external data.


Happy Coding 

Cheers,
Kapil

Thursday, December 26, 2024

Error: Can only be default-imported using the 'esModuleInterop' flag

 

Recently we have faced issue with node js app with following error:


node_modules/@types/express/index"' can only be default-imported using
the 'esModuleInterop' flag

Error Line: import express from "express";

Reason we see esModuleInterop flag was not set as true and ES versions were
not compatible.

To fix this error, we have set

"esModuleInterop" : true

in tsconfig.json in the Compiler-options

Then issue was sorted.

Cheers,
Kapil

Tuesday, December 17, 2024

The `*ngFor` directive was used in the template, but neither the `NgFor` directive nor the `CommonModule` was imported


Recently encountered error below while building an app in Angular

 The `*ngFor` directive was used in the template, but neither the `NgFor` directive nor the `CommonModule` was imported

Pretty simple fix is that imoer common module in your component something like below

import { CommonModule } from '@angular/common';

@Component({
selector: 'app-abc',
templateUrl: './abc-component.html',
styleUrl: './abc.component.scss',
standalone: true,
imports: [CommonModule]
}

Error should disappear.

Enjoy coding !!!

Cheers,
Kapil

Thursday, October 22, 2015

Solved : Eclipse executable launcher error: Unable to locate companion shared library

Recently i was encountered with following errorafter extraccting a ZIP file

Eclipse executable launcher error: Unable to locate companion shared library

To solve this problem that extractor did not extract the content in proper way due to long path of zip file and content within. 

I have reduced the path of zip while extract and it got fix.

Cheers

Kapil 

 

Tuesday, October 13, 2015

Solved : Unable to elevate [error:1812 ] Error andriod


Recently while installing android SDK , I was getting following error

"Unable to elevate" error


Solution I tried :

1. Run installer as a administrator
2. Still an issue then disable Firwall and Antivirus .

It solved the problem.

Cheers ,

Kapil

Thursday, January 30, 2014

How to enable logging within CXF framework to trace SOAP inbound / outbound headers/requests and how it helped to figure out the problem of production incident

Recently surfaced with the problem in production with conflicts of web services calls , summarizing problem statement and troubleshooting approach :

Problem Statement :
Web service calls were not going through and giving 404 and reason was that something broken into header but enough information was not printing in log .

Troubleshooting Approach : Since we are using CXF framework hence more logging can be enabled which helped to figure out problem and we were able to fix problem with a tactical solution. Following are the steps which would help to trouble shoot Inbound and Outbound soap headers/requests of web services , It may help @ any point in time to discuss further with EIS team and to know the exact reason : Steps to enable logging :

Step 1 : Change in debug level ( in our case it is in local.propeties file) : Add following line in log4j section : log4j.logger.org.apache.cxf = INFO, FILE

Step 2 : Append highlighted (bold) JVM parameter . ( In our case it is in tomcat.generaloption property within properties file) :

tomcat.generaloptions=-Dorg.apache.cxf.Logger=org.apache.cxf.common.logging.Log4jLogger

Step 3 : Change in cxfclient-beans.xml file ( a bean file as part of application ) Add highlighted line into cxf:bus tag :


Step 4 : Do following acitons :

a) stop the server ( tomcat in our case )
b) run ant deploy ( to redeploy JVM option in our case , you may or may not have it if place dirctly into server)
c) start the server ( Tomcat )

it's all done :)

Cheers 

Kapil

Saturday, March 9, 2013

Eclipse : failed to load the jni shared library and returned exit code 13


It's been a long time to write in something in blog due to bust schedule and hard disk crash  , today I got a time re setup my system ...  While setting up jdk and eclipse today I encountered two problems :

1. After installing JDK on my 64 bit machine when i clicked on eclipse it prompted me following message :
         "failed to load the jni shared library"

to fix this I figured out that my eclipse.ini file has old version (1.5) and i have installed 1.6 
  Solutiong which found as below :  make an entry -vm
C:\Program Files\Java\jdk1.6.0_18\bin\javaw.exe (below is copied version to see where i made this entry)


-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
C:\Program Files\Java\jdk1.6.0_18\bin\javaw.exe

-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx384m


2. Even after this after click on eclipse exe , I found another error  " returned exit code 13" and cause is as below :

version of jdk was of 32 bit while of eclipse 64 bit .. I have installed 64 bit version of JDK then to fix this .

Now my eclipse works smoothly with new (JDK1.6) version :). Happy moment for me . 

Cheers 

Kapil 


Sunday, December 9, 2012

Hibernate HSQL Exception : This function is not supported

 
I was testing hibernate with HSQL ..  and during the runnning my program 
I found following exception : 
 
Caused by: 
org.hibernate.exception.GenericJDBCException: This function is not supported
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert 
(StandardSQLExceptionConverter.java:54)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert 
(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert 
(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler. 
continueInvocation(ConnectionProxyHandler.java:146)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.
 invoke(AbstractProxyHandler.java:81)
    at $Proxy23.prepareStatement(Unknown Source)
 
Solution  : 

I found HSQL version was old with the comptibility i was using 1.8.. 
and to solve this problem i have upgraded HSQL version to 2.2.9.
 
And then able to run the programe succefully . 

Cheers 

Kapil 


Wednesday, May 18, 2011

Tips : Debug applicaitons with Tomcat and Eclipse

We can use simple steps to debug the applications with tomcat.

Step 1 . 

Run the startup with following args in command prompt under tomcat bin dir

catalina.bat jpda start
 
or 
 
startup.bat jpda start
 
Note : Your tomcat with start with the port 8000 for debug . 
 
Step 2. 
Open Eclipse  - > Goto Debug configuration 
setup \
host : localhost 
port : 8000 and apply. 
 
Note : Your applciation will be ready to debug with tompact . 
 
 
Cheers
Kapil 

Tuesday, March 15, 2011

Initialize the log4j config with JVM configuration

Following JVM args can easily help to configure the your customized log4j properties for logging purpose

-Dlog4j.configuration=file:/E:/myWorkSpace/Practice/src/config/log4j.properties

Cheers

Thursday, September 9, 2010

JVM option to debug Class loading issue and Conflicts

If we are having any problem and conflicts of classes in various jar file during server load then following option can help to trouble shoot the issue :

java -verbose:class

It will print all classes loading by class loader with respective jar file name.

Cheers

Sunday, March 7, 2010

Debug Independent JAVA applications remotely with ECLIPSE

I have to debug independent batch process with Eclipse so I did following steps for this configuration:

Step1 : run your program using bat or sh file with following args ..

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="8000" com.test.TestMain

Now your java program or application will run on port 8000 as server

Step 2 :

Open debug into Eclipse then launch remote application
and set project , host as 127.0.0.1 and port 8000.

Then your app is ready to debug with Eclipse :)

cheers

Thursday, October 22, 2009

How effective netstat to know your remote connections and troubleshooting of network issue :)

Today in our testing environment we encountered with one problem of open connection during  web service call to other system.
To truoble shoot and resolve this issue in my development PC first I connected to test environment and took help from netstate commands to resolve this issue .
I found quite of interesting commands to know the open / close_wait / time_wait and established connections.
(Don't forgot to give interval if you wanna see in schedule way :)
like netstae -n 2  will schedule it to 2 sec interval and display the all remote connections within this time)

A simple summary tutorials of netstat is as below:


Netstat (network statistics) is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface statistics. It is available on Unix, Unix-like, and Windows NT-based operating systems.

Parameters used with this command must be prefixed with a hyphen (-) rather than a slash (/).

-a : Displays all active TCP connections and the TCP and UDP ports on which the computer is listening.

-b : Displays the binary (executable) program's name involved in creating each connection or listening port. (Windows only)

-e : Displays ethernet statistics, such as the number of bytes and packets sent and received. This parameter can be combined with -s.

-i : Displays network interfaces and their statistics (not available under Windows)

-n : Displays active TCP connections, however, addresses and port numbers are expressed numerically and no attempt is made to determine names.

-o : Displays active TCP connections and includes the process ID (PID) for each connection. You can find the application based on the PID on the Processes tab in Windows Task Manager. This parameter can be combined with -a, -n, and -p. This parameter is available on Microsoft Windows XP, 2003 Server (not Microsoft Windows 2000)).

-p Windows: Protocol : Shows connections for the protocol specified by Protocol. In this case, the Protocol can be tcp, udp, tcpv6, or udpv6. If this parameter is used with -s to display statistics by protocol, Protocol can be tcp, udp, icmp, ip, tcpv6, udpv6, icmpv6, or ipv6.

-p Linux: Process : Show which processes are using which sockets (similar to -b under Windows)

-r : Displays the contents of the IP routing table. (This is equivalent to the route print command under Windows.)

-s : Displays statistics by protocol. By default, statistics are shown for the TCP, UDP, ICMP, and IP protocols. If the IPv6 protocol for Windows XP is installed, statistics are shown for the TCP over IPv6, UDP over IPv6, ICMPv6, and IPv6 protocols. The -p parameter can be used to specify a set of protocols.

-v : When used in conjunction with -b it will display the sequence of components involved in creating the connection or listening port for all executables.

Interval : Redisplays the selected information every Interval seconds. Press CTRL+C to stop the redisplay. If this parameter is omitted, netstat prints the selected information only once.

/? : Displays help at the command prompt. (only on Windows)


To display the statistics for only the TCP or UDP protocols, type one of the following commands:

netstat -s -p tcp

netstat -s -p udp

To display active TCP connections and the process IDs every 5 seconds, type the following command (works on Microsoft XP and 2003 only):

netstat -o 5

OS X version

netstat -w 5

To display active TCP connections and the process IDs using numerical form, type the following command (works on Microsoft XP and 2003 only):

netstat -n -o

Popular Posts