Express js CORS Middleware not working in my server? - javascript

I'am using CORS middleware in express js.
const express = require ("express")
const cors = require("cors")
const PORT = process.env.PORT || 5000
const app = express()
// ***** 1st solution *****
// app.use((req,res,next)=>{
// res.header("Access-Control-Allow-Origin","*")
// })
// ***** 2nd solution *****
// app.use(cors())
// ***** 3rd solution *****
// app.options("*",cors())
app.all("*",(req,res,next)=>{res.send("helloooo")})
app.listen(PORT,()=>{console.log(`Server is running on port ${PORT}`)})
only first solution works fine but using CORS middleware has no effect
I tried also dynamic origins solution from docs and adding options to my cors with origin containg google url but have the same issues
I test it from google trying to fetch my server like that
fetch("http://localhost:5000").then((res)=>res.text()).then(console.log())
then it gives error
Access to fetch at 'http://localhost:5000/' from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
however using thunder client to send request didn't gave me error but working fine
however using thunder client to send request didn't gave me error but working fine.
how can I solve this problem using CORS middleware,
instead of adding header directly to all my responses to all origins

Related

how to change a file in github using simple-git npm pacakge [duplicate]

I want to fetch the data of this url https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt#L2
I am trying to use fetch api to get the data but i am getting cors error
Here is what i am trying to do
async function showmodal1() {
console.log("hello")
const data = await
fetch('https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt');
console.log(data)
}
showmodal1();
Is there any way to get the data of the github txt file
I tried finding this over internet but i was unable to find anything
Thank you for your help in advance
Edit:
Access to fetch at 'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. changelog.html:361
GET https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt net::ERR_FAILED
showmodal1 # changelog.html:361
(anonymous) # changelog.html:365
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
changelog.html:364
Uncaught (in promise) TypeError: Failed to fetch
here is the error log
Edit2:
Promises/Fetch in JavaScript: how to extract text from text file
Reading code from GitHub as text (raw) in a web page
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Here are the links that I discovered before writing the question
Your code is being deployed from 'http://127.0.0.1:5500' which is not the same as 'http://github.com' and is being blocked by CORS (which is enabled on modern browsers by default). You need to add the specific headers to your development server.
The * in the Access-Control-Allow-Origin header allows communication to any (wildcard) domain.
Sample:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, Content-Type, Authorization"
There are as well browser extensions that "unblock" CORS but would be considered unfavourable.
Edit:
Fetch the raw source too. The URL is available by clicking the raw button on the URL you were trying to access in your request.
Edit2:
here is the code that will work
const url1 = 'https://raw.githubusercontent.com/ProjectSakura/OTA/10/changelog/changelog_beryllium.txt'
const response = await fetch(url1);
const data = await response.text();
console.log(data);
On client side you will not be able to fetch GitHub text file as browser enforces cross browser origin policies as a security measure. Your source itself must set the relevant CORS headers to allow that. You can however do it from server side. Create a node server like below using express, and then try accessing data from your own server instead.
server.js
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
app.use(cors());
app.get('/txt_response', async (req, res) => {
const resp = await fetch('https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt');
const textResp = await resp.text();
res.json(textResp);
});
app.listen('9000');
Now you can use http://localhost:9000/txt_response as your endpoint to query data in your client-side code.
Take a look here and scroll down to "Supplying request options":
fetch(
'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt',
{
mode: 'no-cors'
}
)

CORS: response to preflight request doesn't pass access control check - How to solve it on localhost?

I am quite a beginner with JavaScript and I am trying to write a script that checks whether a website, let's say https://example.comreturns 404 status code or 200, and depending on the result, I'll access it or not. I am doing this on front end side. I don't have a server side, as the website is a static one that does not use a database.
I am doing this using XMLHttpRequest.
url = $("#foo").attr("href")
function UrlExists(ur)
{
var http = new XMLHttpRequest();
http.open('GET', ur, true);
http.setRequestHeader("Access-Control-Allow-Origin", "http, https");
http.setRequestHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTONS");
http.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
http.send();
console.log(http.status);
}
UrlExists(url)
The problem is when I run this script, the following Exception is being thrown:
Access to XMLHttpRequest at 'http://example.com' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
From what I read so far, it is rather CORS issue than JavaScript and I could not find a solution so far.
Can anybody help me with this issue and explain me why?
I have checked other questions on SO and so far, I did not find a working solution. I am open to other solution too if there are any. Thank you so much!
I much appreciate your time!
UPDATE 1:
Unfortunately, I am still struggling with this issue. I've read a lot about CORS policy, the problem is that I can't get how I should I can safely allow headers to be sent through request from my server to another one.
The resources are: an HTML page and some JS code in it. As I have mentioned above, I am trying to send a request from my site to another one to check the status of that website, and if 404 pops, I want to redirect my user.
You need to set the CORS header on your web server. It is disabled by default for security reasons.
For example, in Nginx, you may do
add_header Access-Control-Allow-Origin example.com;
In case you are using a hosting service that does not allow webserver config modification, you may add the required headers to .htaccess file in your as shown under. In other words, place it in the root of your project where you have your index.html. Also, change the permissions to 644.
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
References:
https://stackoverflow.com/a/20082724/2777988
https://blog.container-solutions.com/a-guide-to-solving-those-mystifying-cors-issues
I'm using Flutter and Nodejs (in HEROKU), this worked for me:
FLUTTER:
//FLUTTER
...
final headers = <String, String>{
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
};
final resp = await http.post(//here we make the req
Uri.parse(url),
body: convert.jsonEncode(body),
headers: headers,
);
///
SERVER NODEJS IN HEROKU:
///SERVER NODEJS IN HEROKU
const express = require('express');
const cors = require("cors"); //this is a library to config easily cors
const app = express();
app.use(express.json());
app.use(cors({ origin: true })); // enable origin cors
app.post('/',async(req,res)=>{
...
///
Then i solved mixed content (with heroku), and cors problem

how to fix GET net::ERR_FAILED

i am very very new to backend and express js. I wanted to fetch data from my rest api but it is sending this error net::ERR_FAILED.
//my api
const express = require("express");
const app = express();
app.get("/", (req, res)=>{
res.send("hello world!!!")
})
const videos = {
"source": "....com",
"url": "...com"
}
app.get("/api/home", (req, res)=>{
res.send(videos)
})
app.listen(3500, ()=>console.log("listening at port 3500..."))
<!DOCTYPE html>
<html>
<head>
<title>Hey</title>
</head>
<body>
<button onclick="init()">hey</button>
<script>
function init(){
const url = "http://localhost:3500/api/home"
fetch(url).then(res=>res.json()).then(result=>{
console.log(result)
})
}
</script>
</body>
</html>
I want to console log the data videos from the api when i click the button, but its not working.
it even says:
Access to fetch at 'http://localhost:3500/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.html:12 GET http://localhost
Because your front-end service address port and back-end service address port are different, Cross-Origin Resource Sharing is triggered. That's why you got the error in the console of the browser.
In order to enable CORS, we can use cors middleware.
Or, use a http-proxy-middleware to proxy your API to the target server.
Frontend => local HTTP server => target server.
I had similar issue.
Check /etc/hosts on your machine and
try to add (if does not exists)
127.0.0.1 localhost

How to fetch data from a particular github txt file in html page via javascript

I want to fetch the data of this url https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt#L2
I am trying to use fetch api to get the data but i am getting cors error
Here is what i am trying to do
async function showmodal1() {
console.log("hello")
const data = await
fetch('https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt');
console.log(data)
}
showmodal1();
Is there any way to get the data of the github txt file
I tried finding this over internet but i was unable to find anything
Thank you for your help in advance
Edit:
Access to fetch at 'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. changelog.html:361
GET https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt net::ERR_FAILED
showmodal1 # changelog.html:361
(anonymous) # changelog.html:365
dispatch # jquery.min.js:3
r.handle # jquery.min.js:3
changelog.html:364
Uncaught (in promise) TypeError: Failed to fetch
here is the error log
Edit2:
Promises/Fetch in JavaScript: how to extract text from text file
Reading code from GitHub as text (raw) in a web page
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Here are the links that I discovered before writing the question
Your code is being deployed from 'http://127.0.0.1:5500' which is not the same as 'http://github.com' and is being blocked by CORS (which is enabled on modern browsers by default). You need to add the specific headers to your development server.
The * in the Access-Control-Allow-Origin header allows communication to any (wildcard) domain.
Sample:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, Content-Type, Authorization"
There are as well browser extensions that "unblock" CORS but would be considered unfavourable.
Edit:
Fetch the raw source too. The URL is available by clicking the raw button on the URL you were trying to access in your request.
Edit2:
here is the code that will work
const url1 = 'https://raw.githubusercontent.com/ProjectSakura/OTA/10/changelog/changelog_beryllium.txt'
const response = await fetch(url1);
const data = await response.text();
console.log(data);
On client side you will not be able to fetch GitHub text file as browser enforces cross browser origin policies as a security measure. Your source itself must set the relevant CORS headers to allow that. You can however do it from server side. Create a node server like below using express, and then try accessing data from your own server instead.
server.js
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
app.use(cors());
app.get('/txt_response', async (req, res) => {
const resp = await fetch('https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt');
const textResp = await resp.text();
res.json(textResp);
});
app.listen('9000');
Now you can use http://localhost:9000/txt_response as your endpoint to query data in your client-side code.
Take a look here and scroll down to "Supplying request options":
fetch(
'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt',
{
mode: 'no-cors'
}
)

Error occurs when retriving data from Firebase

Hi I stored my mp3 files inside Storage in Firebase. Set permissions under Rules tab to be:
allow read, write, request;
In order to take the files from there I use react-axios.
When I load my page, I get an error that the request has been blocked by CORD policy:
Access to XMLHttpRequest at
'gs://******.appspot.com/****/****' from origin 'http://localhost:3000'
has been blocked by CORS policy: Cross origin requests are only
supported for protocol schemes: http, data, chrome, chrome-extension,
https.
I installed gsutil and then I ran the command:
gsutil cors set cors.json gs://****.appspot.com
I did not get any errors for running this command.
This is the cors.json file:
[
{
"origin": ["http://localhost:3000","gs://******.appspot.com"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]
However, when I load my website, I still get the same error...
As the error message states cross origin requests are only allowed for certain protocols. This is a security measure implemented in most browsers. If you are interested why this policiy is what it is, theres a good article on codecademy about that.
My suggested solution for that problem would be to setup a backend api server on that host as well, let it query the needed information from the db, add the necessary CORS headers, and send it to the browser running your frontend.
You could do that using node.js utilizing express.js.
Please see below example.
const cors = require('cors');
const express = require('express');
const app = express();
function getmusicfunction(req, res) {
console.log('GET /getmusic');
# query the db for your file here and store it into your body bariable
res.send(body);
}
const corsOptions = {
origin: '*',
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
app.get('/getmusic', (req, res) => getmusicfunction(req, res));
const port = 6667;
app.listen(port, () => console.log('API listening on port ' + port + '!'));
EDIT: I confused Firebase with Firebird. Sorry. I withdraw that answer.
The key parts of the error message are:
Cross origin requests are only supported for protocol schemes
And
Access to XMLHttpRequest at
'gs://******.appspot.com/****/****' from origin 'http://localhost:3000'
You're trying to access a URL starting with gs:// from JavaScript that runs on http://. Those are two different protocols, and the error message says that this is not allowed.
To download a file from Cloud Storage you typically use:
either a download URL you generate for the file, which is a publicly readable (but unguessable) URL. The download URL starts with https:// so is eligible for cross-original requests from your page. See the Firebase documentation on downloading a file via a URL.
or you use the Firebase SDK for accessing the data. The Firebase SDK uses its own protocol, which is not affected by the cross-origin requirements. You could use the gs: URL you now use with that SDK. It looks like this approach is not available in the JavaScript SDK.

Categories

Resources