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({
This blog is dedicated to share my experience during my development as a purpose of notes and explorer various web / enterprise technologies like JAVA , JEE , Spring ,hybris, Portal , Jquery , RAI , JMS, Weblogic , SSL , Security, CS, MAC< Linux, Windows, Search, IOT, Arduino, Machine Learning, Tips, Angular, Node JS, React, Mac, Windows, Stack, Exception, Error etc. with examples.
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({
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.
cors PackageThe easiest way to handle CORS in Node.js is by using the popular cors middleware package.
cors Package:bashnpm install cors
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');
});
If you don't want to use the cors package, you can manually set CORS headers in your responses.
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');
});
If you are still encountering CORS issues:
Origin header.PUT, DELETE, and other methods, browsers send a preflight OPTIONS request to check permissions. Ensure your server handles this method.If you're testing locally and don't want to configure strict CORS rules, you can allow all origins temporarily:
app.use(cors({ origin: '*' }));
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.
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 undefinedThis 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.
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.
Undefined or null data:
const items = undefined;
items.map(item => console.log(item)); // TypeErrorAsynchronous 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)); // TypeErrorIncorrect initial value:
You might set the state to undefined or forget to initialize it as an empty array.
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 errorOptional chaining (?.) prevents accessing properties or methods on undefined or null.
items?.map(item => console.log(item)); // No error, but does nothing if items is undefinedUsing default parameters or the || operator ensures a fallback array if the value is undefined.
function processItems(items = []) {
items.map(item => console.log(item));
}(items || []).map(item => console.log(item));mapExplicitly 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');
}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>
);If you encounter this error, follow these steps to debug it:
Log the Variable:
Use console.log to check the value of the variable before calling map.
console.log(items);Check Data Flow: Trace the origin of the variable to ensure it’s being set correctly.
Handle Edge Cases:
Consider scenarios where the variable might be undefined or null, especially when working with dynamic or external data.
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
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
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 . CheersKapil