Can't get token from server using fetch or axios - reactjs

I'm using ReactJs to build a video call app.
I also up agora-token-service into railway. Testing is oke. But when i try to fetch data, it's has a ploblem, I also tried to fix it but it didn't work. mode: 'no-cors also didn't work
i need a solution please!

You are using http and trying to access content from https thats way it's giving this error.
try to host this website or you can use temporary service like ngrok
use npm i ngrok

See enabling CORS references below, hope this helps.
How to allow CORS in react.js?
It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
In response, the server returns a Access-Control-Allow-Origin header with Access-Control-Allow-Origin: *, which means that the resource can be accessed by any origin.
Access-Control-Allow-Origin: *
This pattern of the Origin and Access-Control-Allow-Origin headers is the simplest use of the access control protocol. If the resource owners at https://bar.other wished to restrict access to the resource to requests only from https://foo.example (i.e., no domain other than https://foo.example can access the resource in a cross-origin manner), they would send:
Access-Control-Allow-Origin: https://foo.example
Note: When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.

Related

Getting Access-Control-Allow-Headers in preflight error

I have created angular js app in which I have integrate twitch api , the api is
return $http({
url: "https://api.twitch.tv/kraken/streams",
method: "GET",
params: { channel: channel, limit: 1 },
headers: { "Client-Id": "XXXXXXXXXXXXXXX" }
})
the problem is when I reload the page the api is working but when my state changes without page reload I am getting cross origin error from this api.
the error is
Failed to load https://api.twitch.tv/kraken/streams?channel=eliazOne&limit=1: Request header field RefreshToken is not allowed by Access-Control-Allow-Headers in preflight response.
anyone has idea how to resolve cross error
When you make a request to a different domain this is called a cross domain request. Also known as a CORS request.
When you POST / PUT data to a different domain it will make an OPTIONS request first. This is to ensure that the server has Access-Control-Allow-Headers in place on the response. These headers should permit access to the domain you are making the request from. If these headers are not present then when the OPTIONS request is made it will fail and the POST / PUT will never be made.
See here for more info https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests
The simple answer is to just add these headers to your server.
I don't know if this is something Angular does on its own by default or if it's a bug elsewhere in your code, but you or Angular is sending a RefreshToken header as part of your failing request, which is not allowed per Access-Control-Allow-Headers response header in the pre-flight OPTIONS request.
$ curl -XOPTIONS https://api.twitch.tv/kraken/streams -is | grep Headers
Access-Control-Allow-Headers: Accept, Accept-Language, Authorization, Client-Id, Twitch-Api-Token, X-Forwarded-Proto, X-Requested-With, X-Csrf-Token, Content-Type, X-Device-Id
This is something all cross-origin requests do. The browser sends an OPTIONS request to make sure the real request it's about to make is allowed by the criteria set by the cross-origin server.
You need to add a ?callback=? with the URL you are passing along with a callback function. Please follow the link How to use JQuery to Access Twitch streams
This is JQuery example but the concept is same.
$.getJSON('https://api.twitch.tv/kraken/streams/' + name + '?callback=?',
function(channel){
if (channel["stream"] == null) {
$("#all").append("<p>" + channel._links.self + "</p>");
}
else {
$("#all").append("<p>Fail</p>");
}
});
});

Activiti REST returns 401 after GET request

When i tried to send a GET request to Activiti REST URL, using POSTMAN and configuring an authorization parameter (kermit:kermit) it works like a charm.
But when i tried to do the same thing, only with Angular $http service, it returns the following error:
XMLHttpRequest cannot load http://localhost:8080/activiti-rest/service/repository/deployments. 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:8081' is therefore not allowed access. The response had HTTP status code 401.
Here is my controller:
(function() {
'use strict';
angular
.module('doktorat-app-test')
.controller('TestController', TestController);
TestController.$inject = ['$http', '$base64'];
function TestController($http, $base64) {
var tcr = this;
$http.defaults.headers.common['Authorization'] = 'Basic ' + $base64.encode('kermit:kermit');
tcr.text = 'ssdsds';
$http.get('http://localhost:8080/activiti-rest/service/repository/deployments')
.then(function(response){
tcr.text = response.data;
});
}
})();
Has anyone encountered on similar error?
Spent more then 2 days trying to resolve this issue, but without any success.
P.S. I am using NodeJS http-server to run my Angular App, which runs on port 8081.
Since you are trying to access rest api which is on http://localhost:8081/ From http://localhost:8080/, browser will check if your server implement CORS using preflight request. You can get detail about CORS on below url:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Normally application hosted in one server will not be allowed to access the resources hosted in other sever.This restriction is implemented by all most all browser now a days.
In order to make it work, your rest api server has to tell that some other servers will also be allowed to call. For this , you need to implement CORS filer in your rest api server.
Since you didn't specify which langauge you are using in REST, i am providing an open source CORS filter library for JAVA:
http://software.dzhuvinov.com/cors-filter.html
which solves your problem.
To allow CORS for a specific domain you can use a middleware as below:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8081");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With");
next();
});

Cross Origin request blocked in Firefox

I'm having a problem where by the cross origin requests from my Angular JS application work fine in Chrome but not in Firefox.
The error received in firefox is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at https://api.domain.eu/join/joinstatus. (Reason:
CORS header 'Access-Control-Allow-Origin' does not match
'https://www.domain.eu, https://www.domain.eu').
I can make requests successfully until I add an Authorization header to the request.
My server (ASP.Net Web API running on IIS) has the following headers set up:
Access-Control-Allow-Origin: https://www.domain.eu
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Credentials: true
Firefox successfully pre-flights the request with an OPTIONS request. Looking through this I can see the sent Origin header is contained in the returned Access-Control-Allow-Origin header.
In fact, for some reason the returned Access-Control-Allow-Origin header has my domain name twice (despite specifying it once in config) e.g.
Access-Control-Allow-Origin: https://www.domain.eu, https://www.domain.eu
That aside what is the difference between Firefox and Chrome in this regard?
What else do I need to do so that this will work in Firefox?
UPDATE
I have noticed that if I set my headers as follows...
`Access-Control-Allow-Origin: https://www.domain.eu'
... then the pre-flight OPTIONS request works fine. The Access-Control-Allow-Origin header is the same in both the request and the response. However the actual GET request then fails with the error above.
If I modify my headers as follows:
Access-Control-Allow-Origin: https://www.domain.eu, https://www.domain.eu
... (which is what Firefox alluded to in the error), then the actual pre-flight OPTIONS request fails as this time Firefox just expects a single value of https://www.domain.eu in the header.
Try:
Access-Control-Allow-Origin: https://www.domain.eu, https://domain.eu
Access-Control-Allow-Origin: https://*.domain.eu, http://*.domain.eu
Access-Control-Allow-Origin: domain.eu
Access-Control-Allow-Origin: *.domain.eu
EDIT:
Try:
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Access-Control-Request-Method: GET, POST, OPTIONS, PUT, DELETE
Docs:
Access-Control-Allow-Origin
A returned resource may have one Access-Control-Allow-Origin header, with the following syntax:
Access-Control-Allow-Origin: <origin> | *
The origin parameter specifies a URI that may access the resource. The browser must enforce this. For requests without credentials, the server may specify * as a wildcard, thereby allowing any origin to access the resource.
For example, to allow http://mozilla.com to access the resource, you can specify:
Access-Control-Allow-Origin: http://mozilla.com
You must only specify a single URI or *
This problem was caused by essentially having the wrong combination of NuGet packages in my solution. Owin and Web API CORS had both been used causing the headers to get mixed up.
I resolved this by going back to basics and working out what packages I needed and the problem went away.
you need to enable CORS in your web API project.
Check this out!

Issue with CORS after adding Stormpath Angular SDK

I am working on SPA MEAN app, I was developing it against Apiary mock APIs, which has the following CORS headers set:
Access-Control-Allow-Methods → OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
Access-Control-Allow-Origin → *
Access-Control-Max-Age → 10
It all works fine and angular can access it using $http angular service just fine. However after adding Stormpath Angular SDK all these requests fail with following error:
XMLHttpRequest cannot load https://xxx.apiary-mock.com/workshops?type=favourite. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:8000' is therefore not allowed access.
I am trying to get to figure out why these requests are rejected and at what point these headers are added?
Thank you for finding this issue. The Stormpath Angular SDK does have an interceptor which sets the withCredentials: true flag for all requests. Please see the code here.
The intention is to ensure that our authentication cookies are always sent, even in a cross-domain situation. But I can see how this will be problematic if your Angular application is talking to other APIs that don't require cookies to be sent.
As a workaround, you can override our interceptor by simply adding another one:
angular.module('myapp', [
'stormpath',
'stormpath.templates'
]).config(function ($httpProvider) {
$httpProvider.interceptors.push(function() {
return {
request: function(config) {
config.withCredentials=false;
return config;
}
};
});
});
I've created an issue to discuss a better solution: https://github.com/stormpath/stormpath-sdk-angularjs/issues/72
Any time you have a SPA client served from one domain (e.g. localhost:8080) and you want that client to access an API on another domain (xxx.apiary-mock.com), the browser requires that the server domain add CORS headers correctly.
If the client and server domains are different, the browser's security model requires the server to indicate which client domains may access the server by setting the Access-Control-Allow-Origin response header (in addition to other relevant Access-Control-* headers).
I have how to work around it add these headers to apiary:
+ Response 200 (application/json)
+ Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
Access-Control-Allow-Origin: http://localhost:8000
I am still trying to figure out where does Stormpath make those headers required though.

AngularJS not detecting Access-Control-Allow-Origin header?

I am running an angular app on a local virtualhost (http://foo.app:8000). It is making a request to another local VirtualHost (http://bar.app:8000) using $http.post.
$http.post('http://bar.app:8000/mobile/reply', reply, {withCredentials: true});
In the Network tab of Chrome Developer Tools I of course see the OPTIONS request, and the response includes the header:
Access-Control-Allow-Origin: http://foo.app:8000
However, the POST request is cancelled with the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://foo.app:8000' is therefore not allowed access.
Has anyone experienced this? The Access-Control-Allow-Origin header is very plainly included in the response of the OPTIONS request, so I can't for the life of me figure out why the POST is acting the header was missing.
Access-Control-Allow-Credentials is also set to true.
It's a bug in chrome for local dev. Try other browser. Then it'll work.
There's a workaround for those who want to use Chrome. This extension allows you to request any site with AJAX from any source, since it adds 'Access-Control-Allow-Origin: *' header to the response.
As an alternative, you can add this argument to your Chrome launcher: --disable-web-security. Note that I'd only use this for development purposes, not for normal "web surfing". For reference see Run Chromium with Flags.
As a final note, by installing the extension mentioned on the first paragraph, you can easily enable/disable CORS.
I was sending requests from angularjs using $http service to bottle running on http://localhost:8090/ and I had to apply CORS otherwise I got request errors like "No 'Access-Control-Allow-Origin' header is present on the requested resource"
from bottle import hook, route, run, request, abort, response
#https://github.com/defnull/bottle/blob/master/docs/recipes.rst#using-the-hooks-plugin
#hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
I experienced this exact same issue. For me, the OPTIONS request would go through, but the POST request would say "aborted." This led me to believe that the browser was never making the POST request at all. Chrome said something like "Caution provisional headers are shown" in the request headers but no response headers were shown. In the end I turned to debugging on Firefox which led me to find out my server was responding with an error and no CORS headers were present on the response. Chrome was actually receiving the response, but not allowing the response to be shown in the network view.
CROS needs to be resolved from server side.
Create Filters as per requirement to allow access and add filters in web.xml
Example using spring:
Filter Class:
#Component
public class SimpleFilter implements Filter {
#Override
public void init(FilterConfig arg0) throws ServletException {}
#Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, resp);
}
#Override
public void destroy() {}
}
Web.xml:
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>
com.abc.web.controller.general.SimpleFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I just ran into this problem today. It turned out that a bug on the server (null pointer exception) was causing it to fail in creating a response, yet it still generated an HTTP status code of 200. Because of the 200 status code, Chrome expected a valid response. The first thing that Chrome did was to look for the 'Access-Control-Allow-Origin' header, which it did not find. Chrome then cancelled the request, and Angular gave me an error. The bug during processing the POST request is the reason why the OPTIONS would succeed, but the POST would fail.
In short, if you see this error, it may be that your server didn't return any headers at all in response to the POST request.
It can also happen when your parameters are wrong in the request. In my case I was working with a API that sent me the message
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401."
when I send wrong username or password with the POST request to login.
Instead of using $http.get('abc/xyz/getSomething') try to use
$http.jsonp('abc/xyz/getSomething')
return{
getList:function(){
return $http.jsonp('http://localhost:8080/getNames');
}
}
If you guys are having this problem in sails.js just set your cors.js to include Authorization as the allowed header
/***************************************************************************
* *
* Which headers should be allowed for CORS requests? This is only used in *
* response to preflight requests. *
* *
***************************************************************************/
headers: 'Authorization' // this line here

Resources