Response for preflight is invalid (redirect) - xmlhttprequest

I'm trying to fetch quotes history from yahoo api:
Yahoo Historical quotes
I encountered cross-origin error and I tried to resolve it by setting the correct xmlHttpRequest header. I have followed recommendation from other posts but no success.
I don't want to use Yahoo YQL, as it limits response to ~2 years quotes history.
Here is my code:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
console.log(this.getAllResponseHeaders())
}
};
xhttp.open("GET", "http://chart.finance.yahoo.com/table.csv?&a=0&b=1&c=2011&d=3&e=17&f=2017&s=YHOO", true);
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Content-Type", "text/plain");
xhttp.setRequestHeader("cache-control" , "private");
xhttp.setRequestHeader("Access-Control-Allow-Methods" , "DELETE, HEAD, GET, OPTIONS, POST, PUT");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition, Content-Description");
xhttp.send();
}
</script>
</body>
</html>

Related

Vue + Golang : Access to XMLHttpRequest at [Apiurl] from origin has been blocked by CORS policy: Request header field authorization is not allowed

I am beginner to Vuejs & golang.
I got following error when I try to send Authorization token thorugh header while calling api from vue axios.
Access to XMLHttpRequest at 'http://localhost:5000/greet/hello' from origin 'http://localhost:5500' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
[Actually I got error in my another project. but to understand solution I implement this in simple following project. So anyone can test code at their end and provide solution]
App.go
package main
import (
"fmt"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(cors.Default())
router.Use(Authenticate())
v1 := router.Group("/greet")
{
v1.POST("/hello", handleFunc)
}
router.Run(":5000")
}
func handleFunc(c *gin.Context) {
var student struct {
Name string `json:"name"`
}
if c.BindJSON(&student) != nil {
c.JSON(400, gin.H{"message": "Provide required details."})
c.Abort()
return
}
message := fmt.Sprintf("%s%s", "Good Morning ", student.Name)
c.JSON(200, gin.H{"message": message})
}
func Authenticate() gin.HandlerFunc {
return func(c *gin.Context) {
requiredToken := c.Request.Header["Authorization"]
if len(requiredToken) == 0 {
c.JSON(400, gin.H{"message": "No token found"})
c.Abort()
return
}
fmt.Println(requiredToken)
c.Next()
}
}
index.html
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
</head>
<body>
<div id="app" class="container m-5">
<p>{{name}}</p>
<input type="text" class="form-control col-3" placeholder="Enter Name" v-model="name"/><br>
<button #click="onButtonClick" class="btn btn-info">CALL API</button>
</div>
<script src="index.js"></script>
</body>
</html>
index.js
var app = new Vue({
el: '#app',
data: {
name: ""
},
methods: {
onButtonClick() {
axios
.post("http://localhost:5000/greet/hello",
{
Name: this.name
},
{
headers: {
Authorization: "HEY"
}
})
.then((response) => {
if (response.status == 200) {
alert(response.data.message);
}
})
.catch((error) => {
console.log(error);
alert(error.response.data.message);
});
},
}
})
Basically you are not allowed to have Allowed-Origin: * when sending the Authorization header so you'll have to specify the domain that is allowed, you can achieve this by changing the CORS middleware instead of using the default router.Use(cors.Default())
you could use something like this
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:5500"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
you can also use the AllowOriginFunc cors.Config property for a dynamic logic (in case you want to support multiple domains).
Notice how the AllowOrigin property contains the domain of your vue project. Obviously you can allow more headers but the ones listed here are the ones you were allowing previously by using the Default config

How to update webrtc xirsys from v2 to v3?

I am currently testing and working on the webrtc firebase demo by Muaz khan. In one of the files it uses Xirsys and the credentials used are the ones of Muaz Khan. The xirsys details are of version v2. Currently Xirsys uses version V3. I was wondering how to change the former code to the new code.
The former code which is working in the demo is
<script type="text/javascript" src="https://gc.kis.v2.scr.kaspersky-
labs.com/EC7AD6FB-B1E9-9D47-B085-7DB58B77DF98/main.js" charset="UTF-8">
</script><script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var url = 'https://service.xirsys.com/ice';
var xhr = createCORSRequest('POST', url);
xhr.onload = function () {
window.parent.postMessage({
iceServers: JSON.parse(xhr.responseText).d.iceServers
}, '*');
};
xhr.onerror = function () {
console.error('Woops, there was an error making xhr request.');
};
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
window.addEventListener('message', function (event) {
if (!event.data || typeof event.data !== 'string') return;
if(event.data == 'get-ice-servers') {
xhr.send('ident=muazkh&secret=59d93f26-5b89-11e5-babe-
d61aeb366a63&domain=webrtcexperiment-webrtc.netdna-
ssl.com&application=default&room=default&secure=1');
}
});
</script>
According to the new Xirsys documentation it should be like
<!-- JS Get ICE STUN and TURN list -->
<DOCTYPE>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js">
</script>
<script>
$( document ).ready( function () {
$.ajax ({
url: "https://global.xirsys.net/_turn/muazkh/",
type: "PUT",
async: false,
headers: {
"Authorization": "Basic " + btoa("muazkh:59d93f26-5b89-11e5-babe-d61aeb366a63")
},
success: function (res){
console.log("ICE List: "+res.v.iceServers);
}
});
})
</script>
</head>
<body>
</body>
</html>
What I did was this but did not work
<head><script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var url = 'https://global.xirsys.net/_turn/muazkh/default/default';
var xhr = createCORSRequest('PUT', url);
xhr.onload = function () {
window.parent.postMessage({
iceServers: JSON.parse(xhr.responseText).v.iceServers
}, '*');
};
xhr.onerror = function () {
console.error('Woops, there was an error making xhr request.');
};
xhr.setRequestHeader("Authorization", "muazkh:59d93f26-5b89-11e5-babe-d61aeb366a63");
window.addEventListener('message', function (event) {
if (!event.data || typeof event.data !== 'string') return;
if(event.data == 'get-ice-servers') {
xhr.send();
}
});
</script>
</head>
Will greatly appreciate any help here. Thanks
Looks like a headers issue. The authorization header should use the "Basic" authentication scheme.
Please change your XMLHttpRequest's "setRequestHeader" to:
xhr.setRequestHeader("Authorization", "Basic "+ btoa("muazkh:59d93f26-5b89-11e5-babe-d61aeb366a63") );

Facebook Client-Side Authentication Example - Adding Scope

I'm using the Facebook JS SDK to do Client-Side Authentication per there example located here
<!DOCTYPE html>
<html>
<head>
<title>Facebook Client-side Authentication Example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//'+window.location.hostname+'/channel', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
// respond to clicks on the login and logout links
document.getElementById('auth-loginlink').addEventListener('click', function(){
FB.login();
});
document.getElementById('auth-logoutlink').addEventListener('click', function(){
FB.logout();
});
}
</script>
<h1>Facebook Client-side Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
Login
</div>
<div id="auth-loggedin" style="display:none">
Hi, <span id="auth-displayname"></span>
(logout)
</div>
</div>
</body>
</html>
What I haven't been able to figure out in my mucking around is how to add, to this code, the scope parameter to request access to the email address. Can anyone point me in the right direction?
Thanks!
--- EDIT ---
I've seen this code located in the documentation
FB.login(function(response) {
// handle the response
}, {scope: 'email'});
I guess I'm not sure how to incorporate that into this existing code though because it's not working
document.getElementById('auth-loginlink').addEventListener('click', function(){
FB.login();
});
If anyone can update the above line to incorporate the extra scope parameter I'm eager to try it.
Simple solution for you. Just add those parameters to the FB.login() function.
FB.login(function(){}, {scope: 'email'});
If you don't need to handle the login response then just provide an empty function.

httprequest call Origin null is not allowed by Access-Control-Allow-Origin

I'm trying to get some data from this imdb api: http://www.deanclatworthy.com/imdb/#usage
However I'm getting errors using this code:
<hmtl>
<head>
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttp = false;
}
}
}
xmlhttp.open("GET", "http://www.deanclatworthy.com/imdb/?q=The+Green+Mile", false);
xmlhttp.send();
var imdbData = xmlhttp.responseText;
//var imdbJSON = eval("(" + imdbData + ")");
alert(imdbData);
</script>
</head>
<body>
<body>
</body>
</html>
The error is this: Origin http://mysite.nl is not allowed by Access-Control-Allow-Origin.
test.html:23Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101
Could someone post a working code on this request? Thank you.
You can't access other server's data like you can your's. It violates the same origin policy. For cross domain requests you could use jQuery and JSONP, see:
http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide
http://remysharp.com/2007/10/08/what-is-jsonp/
If you don't use jQuery you can google "cross domain ajax" or something. Maybe these links give you some ideas
http://snook.ca/archives/javascript/cross_domain_aj
http://alvinabad.wordpress.com/2009/02/13/feb13/
As for the working code request. Well, now that you are aware of the same origin policy, maybe you'll get it to work yourself...

FB.getLoginStatus() not firing

Currently FB.getLoginStatus is not at all firing after the facebook changes with new SDK and OAuth 2.0.
We used to get the response in FB.getLoginStatus and call our callback function that in turn was redirecting
the users to our facebook application.
Please help.
The code snippet -
FB.init({
appId: '<%=ConfigurationManager.AppSettings["APIKey"]%>', // App ID
//channelURL: 'xd_receiver.htm', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
oauth: true // enable OAuth 2.0
//xfbml: true // parse XFBML
});
update_user_is_connected();
function update_user_is_connected()
{
FB.getLoginStatus(function(response)
{
callback();
});
}
function callback() {
var fbURL = "http://apps.facebook.com/" + '<%=Suffix%>' + "/MyPage.aspx";
eval("parent.location='" + fbURL + "'");
}
Now FB.getLoginStatus is not working.
Regards,
KK
I've had the same issue and fixed it by adding true as a second parameter :
FB.getLoginStatus(function(response) {
callback();
},
true);
This disables the cache and forces reloading. See the docs
Just encountered this error whilst trying to check whether the user is already logged in with Facebook as soon as the page finished loading.
If you're trying to do this, you need to wait for facebook sdk to finish loading, Make your call to your checkLoginState() method inside window.fbAsyncInit after FB.init().
This code works very well with me to check login status and request login and fetch oauth info (Name, User Id, Token ... ) based on Java script SDK.
I have some recommendations which are that you have to make sure your application and channel file should be located within your domain which you have setup in your Facebook App settings.
Also make sure you have the div fb-root in your code:
<div id="fb-root"></div>
As shown below
Hope this may help ...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxx', // App ID
channelUrl : 'https://xxxxxxxxxxxxx/channel.html',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
var token = "";
var userId = "";
FB.getLoginStatus(function(response) { // Get Login Status
if (response && response.authResponse) { // Check if User is Logged In
var token = response.authResponse.accessToken; // Get Token
var userId = response.authResponse.userID; // Get User ID
} else {
// alert("Not Auhtenticated");
FB.login(function(response) { // Promot User to Authenticate App
if (response && response.authResponse) {
var token = response.authResponse.accessToken;
var userId = response.authResponse.userID;
}
}, {scope: 'user_likes,friends_likes,publish_stream,read_friendlists,offline_access'}); // Scopes Example...
}
});
};
//Load asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxxxxxxxxxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
My problem was in the window.fbAsyncInit function.
FB.init({
appId : '321677491886687',
cookie : true,
xfbml : true,
version : '3.2'
});
I needed to change 3.2 to v3.2
Kamal,
I believe you can fix your problem by replacing
FB.getLoginStatus(function(response)
{
callback();
});
with
FB.Event.Subscribe('auth.login', callback());
Regards
Make sure all you URLs are correct, I had the same problem while running locally but had the site URL pointing to the production website, once I corrected this, getLoginStatus worked all right.