how to change a file in github using simple-git npm pacakge [duplicate] - 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'
}
)

Related

Express js CORS Middleware not working in my server?

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

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

Cannot call Apache Airflow REST API using JavaScript Fetch API (CORs Error)

Working with Apache Airflow REST API, and having issues with CORS.
When calling the endpoint using the fetch API in JavaScript I get the following error:
Access to fetch at 'my_url/api/v1/dags/example_bash_operator/tasks' from origin 'my_url' 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.
This is how I am calling it:
let url = "my_url/api/v1/dags/example_bash_operator/tasks";
let username = 'my_username';
let password = 'my_password';
let headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
fetch(url, {
headers: headers,
method: 'GET',
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
I also tried adding mode: 'no-cors' but just get the "unexpected end of input" error.
For some background, the following works fine:
starting the airflow webserver and scheduler
accessing the airflow UI
accessing the SwaggerUI authenticating Swagger and calling the REST endpoints with this tool
calling my_url in the address bar of a new browser tab (returns the expected JSON)
I have set the auth_backend in airflow.cfg:
auth_backend = airflow.api.auth.backend.default
Although with the latest REST API version I don't think this makes a difference since everything is set to deny.
I have also set the access control headers in airflow.cfg as described in the docs:
access_control_allow_headers = origin, content-type, accept
access_control_allow_methods = POST, GET, OPTIONS, DELETE
access_control_allow_origin = my_url
...and also tried with wildcard for the access_control_allow_origin:
access_control_allow_origin = *
So the REST calls work fine through Swagger and through the browser address bar, but I cannot call it with fetch using JS. Note that the JS is in an index.html file on the same server (and same root directory) as the airflow files.
The described behavior makes sense, since CORS is used by the browser to prevent attacks from scripts of different resources.
You are still able to fetch via Swagger, Postman or other tools, even through the browser via address bar. But if the policy does not allow to fetch from a different origin, then the browser prevents fetching from your script, which is probably served on a different port. Origin contains host and port.
Your main issue, I cannot help with at the moment.
I've faced the issue of not being able to set the origin policy within the Airflow 2.0 server/API through the (docker-compose) environment variable AIRFLOW__API__ACCESS_CONTROL_ALLOW_ORIGIN.
Maybe it's related to your issue, since I can see from the url of your question (containing the v1), that you're are also using Airflow 2.x.
By the way, the message from chrome is CORS error: Preflight Missing Allow Origin Header, referring to the question in the comments of the original question.

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'
}
)

How can I secure implement third-party API calls using JavaScript in a BigcCommerce store?

I want to make some API requests to the shipping carriers at the BigCommerce product page and I have some credential for that requests which I don't want to show in my JS code. According to the specific environment of BigCommerce I can't make any changes in back end code. I read a lot of similar questions and now have only one question.
Is it only one way to do that using my own API back end web-server which will store credential information and send POST request to the third party API? Then I will receive that information using a POST request via JS to my own API.
I have tried to run Ruby API application on the nginx web-server. However, it was unsuccessful because browser blocked my fetch() request according to the CORS Policy. I tried to add Access-Control-Allow-Origin: * parameter to the server response header writing it in ruby config file but browser didn't recognize it. Also I tried to set up configuration file on the nginx side but that didn't help me with CORS policy response. That's interesting because using Restlet Application I received response from my own API application with correct information and status "ok".
(async function application() {
let dataRuby = {
url: 'http://IP_address/index',
body: {"name": "21312", "year": "2019"}
};
function getApi(data) {
let myInit = {};
myInit.method = "POST";
myInit.body = JSON.stringify(data.body);
myInit.headers = {
'Content-Type': 'application/json'
};
let myRequest = new Request(data.url, myInit);
return fetch(myRequest).then(
res => res.json()
);
}
let response = await getApi(dataRuby);
console.log(response);
})()
Access to fetch at http://IP_address/index from origin 'null' 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.

Categories

Resources