Can't resolve Dropbox.com redirects with Axios or D3-fetch - redirect

I'm trying to fetch data in the browser from a Dropbox link: https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1
Using Axios this works in Node:
axios.get('https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1').then(x => {
console.log('Received correctly')
console.log(x.data);
}).catch(error => {
console.log('Error', error.message);
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
}
console.log(error)
});
https://runkit.com/stevebennett/5dc21d04bbc625001a38699b
However it doesn't work in the browser (click the "Console" tab):
https://codepen.io/stevebennett/pen/QWWmaBy
I just get a generic "Network Error". I see the 301 Redirect being retrieved, which seems perfectly normal, but for some reason, it is not followed.
Exactly the same happens with D3: "NetworkError when attempting to fetch resource."
https://codepen.io/stevebennett/pen/KKKoZYN
What is going on?

This appears to be failing because of the CORS policy. Trying this with XMLHttpRequest directly fails with:
Access to XMLHttpRequest at 'https://www.dropbox.com/s/101qhfi454zba9n/test.txt?dl=1' from origin '...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS isn't allowed on www.dropbox.com itself.

Related

http request is blocked by Cors policy for flutter web

I have an Android, Ios and web app that's using php as a backend. All Api's are working fine in both android and ios but throwing CORS error in web.
Getting error like this
Access to XMLHttpRequest at 'https://example.com/api' from origin 'http://localhost:49168' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried to send
headers: {'Access-Control-Allow-Origin': 'http://localhost:49168',
"Origin": "http://localhost:49168"
},
to http request.
Web is working smoothly if i add CORS extension for chrome. Please help me out
The same problems hit me two weeks ago. For me, the following error is giving me a wrong direction to checking the problem:
Access to XMLHttpRequest at 'https://example.com/api' from origin
'http://localhost:49168' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
It says something about the request, but turns out it had nothing to do with the request. And it also had nothing to do with the web server (apache or nginx in my case).
The solution is by adding header to the response (yes, response) from your backend. I don't know the solution for php code, but I use the following code in my golang backend to add header to the response:
// Adding CORS header to response.
func (server *WebUploadServer) addCorsHeader(res http.ResponseWriter) {
headers := res.Header()
// use your domain or ip address instead of "*".
// Using "*" is allowing access from every one
// only for development.
headers.Add("Access-Control-Allow-Origin", "*")
headers.Add("Vary", "Origin")
headers.Add("Vary", "Access-Control-Request-Method")
headers.Add("Vary", "Access-Control-Request-Headers")
headers.Add("Access-Control-Allow-Headers", "Content-Type, Origin, Accept, token")
headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
}
// Here we handle the web request.
func (server *WebUploadServer) webHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Endpoint hit")
server.addCorsHeader(w) // Here, we add the header to the response
switch r.Method {
case "POST":
// do something here.
case "OPTIONS":
w.WriteHeader(http.StatusOK)
case "GET":
fallthrough
default:
fmt.Fprintf(w, "Sorry, only POST method is supported.")
}
}

Is the LinkedIn REST API accessible client side?

I'm building a React app and Express API with a "Sign in with LinkedIn" feature. I've got my OAuth sorted, so I have an access token now but I keep getting a CORS issue when I try using it to fetch data. Can I make REST API requests directly from my React app (client side)? Or do I need to proxy every request through my own Express server / API?
useEffect(() => {
// get linkedin data
fetch(`https://api.linkedin.com/v2/me`, {
method: 'get',
mode: 'cors',
headers: {
'Connection': 'Keep-Alive',
'Authorization': `Bearer ${accessToken}`
},
}).then(response => response.json()).then(function(data) {
console.log(data);
});
}, []);
Access to fetch at 'https://api.linkedin.com/v2/me' 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.

Yammer REST API - How can I fetch data from a different origin (CORS)?

I have created a Yammer app in "My Apps" and have set my Javascript Origin to my local development URL:
http://localhost:3000
In my React app, I am trying to use the Fetch API to get some data. For example:
const url = 'https://www.yammer.com/api/v1/messages/following.json';
const options = {
method: 'GET',
mode: 'cors',
headers: {
'Authorization': `Bearer ${process.env.REACT_APP_YAMMER_ACCESS_TOKEN}`,
}
};
fetch(url, options).then(function(response) {
console.log(response);
return response.json();
}).then(function(json) {
console.log(json);
});
I get a CORS error:
Access to fetch at
'https://www.yammer.com/api/v1/messages/following.json' 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.
I have my Javascript Origin set in the Yammer dashboard and I have the mode set to CORS in my fetch request. What am I missing?
I got it working with a different URL:
const url = 'https://api.yammer.com/api/v1/messages.json';
I haven't seen this documented anywhere but I saw someone reference it here on another StackOverflow post.

XMLHttpRequest cannot load http://domain.com:8080/socket.io/1/?t=1416289828054 No 'Access-Control-Allow-Origin' header is present

I am creating an application using Licode, this is a video conference application in which i have created a room though the XMLHttpRequest call but no able to make connection using XMLHttpRequest following error occurs.
XMLHttpRequest cannot load http://domain.com:8080/socket.io/1/?t=1416289828054. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.com:3001' is therefore not allowed access. The response had HTTP status code 404.
I am facing this issue even i have implemented following code on server
app.use(function(req, res, next) {
"use strict";
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Origin', 'http://'+req.headers.host+':8000');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE');
res.header('Access-Control-Allow-Headers', 'origin, content-type');
if (req.method == 'OPTIONS') {
res.send(200);
} else {
next();
}
});
thanks in advance for your help.
Seems like I had the similar issue (everything works fine util I deployed it on server). First of all check all firewalls and access to socket port from your computer. In my case, the issue was with F5, see here.
Note:
Because F5 will default protocol identified as http, so we need
disable the http protocol,like this when HTTP_REQUEST { if {
([HTTP::uri] starts_with "/socket.io") } { HTTP::disable } }
Hope, I helped you ;)

ASP.NET MVC Authorize Attribute does a 302 redirect when the user is not authorized

MSDN explicitly says it should do 401 redirect, but I'm getting a 302 redirect on FF, and this is causing problems in AJAX requests as the returned status is 200 (from the redirected page).
http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx
I've found someone else with the same problem:
http://blog.nvise.com/?p=26
Any other solution, besides his?
I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective.
Global.asax:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 302 &&
Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
Context.Response.Clear();
Context.Response.StatusCode = 401;
}
}
Client Side Code:
$(function () {
$.ajaxSetup({
statusCode: {
401: function () {
location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
}
}
});
});
The Authorize attribute does return a Http 401 Unauthorized response. Unfortunately, however if you have FormsAuthentication enabled, the 401 is intercepted by the FormsAuthenticationModule which then performs a redirect to the login page - which then returns a Http 200 (and the login page) back to your ajax request.
The best alternative is to write your own authorization attribute, and then if you get an unauthenticated request that is also an Ajax request, return a different Http status code - say 403 - which is not caught by the formsAuthenticationModule and you can catch in your Ajax method.
I implemented my own custom authorize attribute which inherited from AuthorizeAttribute and ran into the same problem.
Then I found out that since .Net 4.5 there is a solution to this - you can suppress the redirect in the following way:
context.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
Then the response will be a 401 - Unauthorized, along with the HTTP Basic authentication challenge.
More info here
If you are using a ASP.NET MVC 5 Web Application go to App_Start -> Startup.Auth.cs. Check if app.UseCookieAuthentication is enabled and see if CookieAuthenticationOptions is set to LoginPath = new PathString("/Login"), or similar. If you remove this parameter 401 will stop redirecting.
Description for LoginPath:
The LoginPath property informs the middleware that it should change an
outgoing 401 Unauthorized status code into a 302 redirection onto the
given login path. The current url which generated the 401 is added to
the LoginPath as a query string parameter named by the
ReturnUrlParameter. Once a request to the LoginPath grants a new
SignIn identity, the ReturnUrlParameter value is used to redirect the
browser back to the url which caused the original unauthorized status
code. If the LoginPath is null or empty, the middleware will not look
for 401 Unauthorized status codes, and it will not redirect
automatically when a login occurs.