XMLHttpRequest cannot load http://abc.mydomain.org/data/todo.js - javascript

I want to use /data/todo.js file in my reactjs component. I have used axios http request to get this data in my react component i.e.,
import React, { Component } from 'react';
import axios from 'axios';
class TodoList extends Component {
componentWillMount() {
var config = {
headers: {
"Access-Control-Allow-Origin": "http://localhost:8080/",
"Access-Control-Allow-Credentials": true
}
};
axios.get('http://abc.mydomain.org/data/todo.js', config)
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})
}
render() {
return (
<div className="todo-list"></div>
);
}
}
export default TodoList;
It gives an error
XMLHttpRequest cannot load http://abc.mydomain.org/data/todo.js. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

You are trying to access a cross-origin HTTP request from you application, which is by default blocked by the browser.
To access the resource, Cross-Origin Resource Sharing (CORS) should be enabled at the application you are trying to access (In your case http://abc.mydomain.org)
For security reasons, browsers restrict cross-origin HTTP requests
initiated from within scripts. For example, XMLHttpRequest and the
Fetch API follow the same-origin policy. This means that a web
application using those APIs can only request HTTP resources from the
same domain the application was loaded from unless CORS headers are
used.
You can check more on this here

Related

CORS Error while fetching data from Wiki Js (GraphQL)

I'm getting CORS error while fetching data from wiki js graphql endpoint in my react app. I'm using REACT SSR.
here is what I'm doing
App.js
const client = new ApolloClient({
uri: 'https://example-wiki.herokuapp.com/graphql',
cache: new InMemoryCache(),
headers: {
Authorization:
'Bearer exampleToken1234abc',
},
});
api.js
import { useQuery, gql } from '#apollo/client';
const ALL_PAGES_QUERY = gql`
query PageQuery {
pages {
list {
id
title
tags
}
}
}
`;
export const getAllPages = () => {
const { loading, error, data } = useQuery(ALL_PAGES_QUERY);
return {
loading,
error,
data,
};
};
error
Access to fetch at 'https://example-wiki.herokuapp.com/graphql' from origin 'http://localhost:3000' 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.
enter image description here
enter image description here
I've already tried this solution
https://github.com/requarks/wiki/discussions/3056
provided by one of the maintainer of Wiki Js. but its not working at all

calling an x-api-key in the header of an Angular service

I am trying to call an x-api-key in the header of an angular service but am missing something in the syntax. So far my code spits out an authorization error.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class PrecipForecastService {
constructor(private http:HttpClient) { }
getData () {
const url = 'url_here';
const key = 'key_here';
const header = new HttpHeaders({'x-api-key': key});
return this.http.get(url, {headers: header});
}
}
The browser's network tab shows:
Access to XMLHttpRequest at 'url_here' from origin 'localhost:4200' 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.
Yes the key is correct, it worked with the JS fetch module.
Thanks for the help!
Today, I ran into the EXACT same issue.
After checking the network tab in the dev console of Chrome (hit F12),
I found an interesting preflight response:
Here, the access-control-allow-headers deliver the answer to the problem. They simply don't allow X-API-Key, but instead I was able to use access-token and then it worked... at least I didn't get a CORS error anymore.
In my case, the api docs were just 'buggy'.
hth

How to bypass CORS policy when sending get/post request from React JS?

From my React JS app , I need to fetch data from servers in other domains.
However, I am prevented by CORS policy and not able to fetch the data.
Let us assume that my React app is running on localhost:3000 during the development.
I want to make get/post call to another server running on http://myserver.com
The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz
I have installed http-proxy-middleware thru npm and using it in my react app.
Created a setupProxy.js file under src folder with below content :
const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
app.use(
createProxyMiddleware('/data/records' , {
target:'http://ext-server.com',
changeOrigin: true
})
)
}
On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com
getTheData() {
let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);
axios.get(url,
{
headers: {
"Content-Type":"application/json;charset=UTL-8",
"Access-Control-Allow-Origin": "*",
Accept: "application/json",
},
baseURL: 'http://ext-server.com'
}
).then((response) => {
console.log(response["access_token"]);
}).catch(error) => {
console.log("Error: ", error)
}).then(function () {
console.log("always call it")
});
}
In the package.json , I have added :
"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",
But I am still getting below error:
Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.
Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware?
Any help will be very useful!
Thanks
As you can see from MDN the "Access-Control-Allow-Origin": "*" header is a response type header, this means that it should go to in your server response. Also I advise you to not use the * symbol, instead I would rather match it with the origin header in your Request.
The CORS policy is one and only administered by the web server and its settings. To allow CORS requests it has to be implemented on server side. No chance to do it from your client application.
Basically its just a header setting (below example for NodeJS):
res.header("Access-Control-Allow-Origin", "*")
Sending that header will allow requests from every domain.

redash GET request works on POSTMAN but not on axios

On redash I have a query. It's GET request. On POSTMAN it works well.
Query example:
https://app.redash.io/<company name>/api/queries/<query id>/results.json?api_key=<api key>
But on axios it throws:
Network error
And on console written:
Access to XMLHttpRequest at https://app.redash.io/<company name>/api/queries/<query id>/results.json?api_key=<api key> from origin 'http://localhost:3000' 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.
My axios default configs:
import axios from 'axios/index';
import { appVersion } from '../../constants/defaultValues';
const { CancelToken } = axios;
export const source = CancelToken.source();
const api = axios.create({
timeout: 5 * 60 * 1000,
headers: {
version: appVersion,
},
cancelToken: source.token,
});
export default api;
It's not from your code. your code is right
CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API.
You can read more about Cross-Origin Resource Sharing

Getting tweets with React

I'm using the Twit package to pull tweets. I keep getting error 400, and
Failed to load https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=10: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The bulk of this was able to work with vanillajs, but once I imported into React, I've gotten these errors. How do I fix this? I've taken out the API keys for security.
import React, { Component } from 'react';
import Twit from 'twit';
export default class Twitter extends Component {
componentDidMount() {
const T = new Twit({
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
})
let params = {
screen_name: 'twitterdev',
count: 10
};
function getData(err, data, response) {
let tweet = data;
for (var i = 0; i<tweet.length; i++) {
console.log(tweet[i].text);
console.log();
}
}
T.get('statuses/user_timeline', params, getData);
}
render() {
return(
<div></div>
)
}
}
The Twitter API does not support CORS requests. That's what you are trying to do. Accessing API from a different domain. You'll have to create a bespoke url at your local server that proxies the request to the Twitter
API.

Categories

Resources