Search This Blog

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.

Wednesday, January 8, 2025

List of Build in Functions - Oracle

 

 Oracle provides a comprehensive set of built-in functions categorized into various types. Here’s a list of the commonly used categories and functions:

1. String Functions

  • LOWER(char) – Converts to lowercase
  • UPPER(char) – Converts to uppercase
  • INITCAP(char) – Capitalizes the first letter
  • LENGTH(char) – Returns length of a string
  • SUBSTR(char, start, length) – Extracts substring
  • INSTR(char, substring) – Finds position of substring
  • TRIM(char) – Removes leading/trailing characters
  • LPAD(char, length, pad_char) – Left pad
  • RPAD(char, length, pad_char) – Right pad
  • REPLACE(char, search, replace) – Replaces text
  • CONCAT(char1, char2) – Concatenates strings

2. Numeric Functions

  • ABS(number) – Absolute value
  • ROUND(number, decimal_places) – Rounds to n decimal places
  • TRUNC(number, decimal_places) – Truncates to n decimal places
  • MOD(number1, number2) – Remainder of division
  • CEIL(number) – Rounds up to next whole number
  • FLOOR(number) – Rounds down to previous whole number
  • POWER(base, exponent) – Raises to the power
  • SQRT(number) – Square root
  • SIGN(number) – Returns -1, 0, or 1

3. Date Functions

  • SYSDATE – Returns current date and time
  • CURRENT_DATE – Date in current session timezone
  • ADD_MONTHS(date, number) – Adds months to date
  • LAST_DAY(date) – Last day of the month
  • MONTHS_BETWEEN(date1, date2) – Difference in months
  • NEXT_DAY(date, weekday) – Next specified weekday
  • ROUND(date, format) – Rounds date to the nearest unit
  • TRUNC(date, format) – Truncates date to specified unit

4. Conversion Functions

  • TO_CHAR(date_or_number, format) – Converts to string
  • TO_DATE(char, format) – Converts to date
  • TO_NUMBER(char) – Converts to number

5. Aggregate Functions

  • AVG(column) – Average
  • COUNT(column) – Number of rows
  • SUM(column) – Sum
  • MAX(column) – Maximum
  • MIN(column) – Minimum
  • STDDEV(column) – Standard deviation
  • VARIANCE(column) – Variance

6. Conditional Functions

  • CASE WHEN condition THEN result ELSE result END – Conditional logic
  • DECODE(expr, search, result, default) – Compares values
  • NVL(expr1, expr2) – Replace NULL
  • NVL2(expr1, expr2, expr3) – Replace based on NULL check
  • NULLIF(expr1, expr2) – Returns NULL if equal

7. Miscellaneous Functions

  • USER – Returns the current user
  • UID – Returns user ID
  • SYS_CONTEXT(namespace, parameter) – Returns environment context
  • ROWNUM – Row number in result set
  • ROWID – Unique row identifier

This list covers most of the built-in functions you will encounter in Oracle SQL. Each function plays a specific role in manipulating or retrieving data effectively.

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

Popular Posts