Monday, October 17, 2022

Cross-origin resource sharing (CORS) with Express Node.js

https://www.stackhawk.com/blog/react-cors-guide-what-it-is-and-how-to-enable-it/

////////////////////////////////////////////////////////
// Cross-origin resource sharing (CORS)
////////////////////////////////////////////////////////
const cors = require('cors');
app.use(cors());

app.get(
'url',
function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
res.json({ msg: 'This is CORS-enabled for all origins!' });
next();
}
);

app.listen(8080, '127.0.1.1', function () {
console.log('CORS-enabled web server listening on port 8080');
});

https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors

https://stackoverflow.com/questions/35068712/error-listen-eacces-0-0-0-080-osx-node-js

https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/

https://levelup.gitconnected.com/getting-rid-of-origin-has-been-blocked-by-cors-policy-forever-969e161421ca

https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

https://enable-cors.org/server_expressjs.html

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests

https://stackoverflow.com/questions/36878255/allow-access-control-allow-origin-header-using-html5-fetch-api

External URL in React

https://bobbyhadz.com/blog/react-redirect-to-external-url

https://stackoverflow.com/questions/42914666/react-router-external-link

https://stackoverflow.com/questions/71333662/external-link-not-working-when-using-link-from-react-router-dom

https://stackoverflow.com/questions/66905176/how-to-redirect-to-external-url-onclick-in-react

https://stackoverflow.com/questions/47447441/cant-open-new-tab-in-react-adds-localhost3000-on-link

https://www.kindacode.com/article/ways-to-open-an-external-link-in-react/

https://stackoverflow.com/questions/18476373/how-to-add-target-blank-to-javascript-window-location

window.open - open link in a new window

window.location - open link in current window 

Import variables, functions from JavaScript files

https://bobbyhadz.com/blog/react-import-variable-from-another-file

https://stackoverflow.com/questions/38467574/import-javascript-file-and-call-functions-using-webpack-es6-reactjs

https://stackoverflow.com/questions/38467574/import-javascript-file-and-call-functions-using-webpack-es6-reactjs

ES6 JavaScript object destructuring

Extract array from nested object by destructuring:

{
"status": "success",
"time": "2022-10-17T17:09:50.486Z",
"result": 10,
"data": {
"posts": [ { "_id": "id", "image": "url", "link": "url",
"title": "title", "text": "text", "__v": 0, "counter": 1 } ]
}
}
const { data: { posts } = [] } = data; // extracting posts array from data

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

https://www.w3schools.com/react/react_es6_destructuring.asp

https://blog.bitsrc.io/getting-nested-value-by-using-javascript-7828f7768cc7

https://stackoverflow.com/questions/909003/getting-the-first-index-of-an-object

https://dmitripavlutin.com/javascript-object-destructuring/

https://www.deadcoderising.com/2017-03-28-es6-destructuring-an-elegant-way-of-extracting-data-from-arrays-and-objects-in-javascript/

https://itnext.io/using-es6-to-destructure-nested-objects-in-javascript-avoid-undefined-errors-that-break-your-code-612ae67913e9

Sunday, October 16, 2022

Replace all string text between certain characters or symbols

Replace/remove everything inside [] including []:

str.replace(/\[(.+?)\]/g, '')

Replace all text inside [] and leave []:

str.replace(/\[(.+?)\]/g, '[]')

https://stackoverflow.com/questions/14438198/replacing-text-in-body

https://stackoverflow.com/questions/39208444/regex-ignoring-text-between-quotes-html5-attribute-filtering

https://www.codegrepper.com/code-examples/javascript/how+to+exclude+a+specific+tag+name+from+a+javascript+query+search

Fetch data from local JSON file in React

How to access public files in React and fetch JSON data from local file:

http://localhost:3000/data.json // JSON located in /ReactProject/public/data.json

const { data, loading, error } = useFetch('data.json');

https://akhtarvahid.medium.com/how-to-access-fetch-the-local-json-file-to-react-5ce07c43731d

Saturday, October 15, 2022

Fetching JSON data from API with useEffect

import { useEffect, useState } from 'react';

export default function useFetch(url) {
const [data, setData] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
setLoading(true);
fetch(url, {
method: 'GET',
mode: 'cors',
dataType: 'json',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((res) => {
if (!res.ok) {
throw new Error(
`HTTP ${res.status} ${res.statusText}. Fetch ${res.url}`
);
}
return res.json();
})
.then((obj) => {
setData(obj);
console.log(`Fetched ${url}`);
})
.catch((err) => {
setError(err);
console.log(err); // throw new Error || err.message
})
.finally(() => {
setLoading(false);
});
}, [url]);

return { data, error, loading };
}

https://www.codementor.io/@mohammedelhossinyriaad/how-the-useeffect-react-hook-work-1cq3g0g8bd

https://www.smashingmagazine.com/2020/07/custom-react-hook-fetch-cache-data/

https://www.robinwieruch.de/react-hooks-fetch-data/

https://dev.to/shaedrizwan/building-custom-hooks-in-react-to-fetch-data-4ig6

https://www.developerway.com/posts/how-to-fetch-data-in-react

https://use-http.com/#/