CORS policy is blocked - google-chrome-extension

I create simple google chrome extension and I get JSON data but this error is generated
dashboard.html:1 Access to XMLHttpRequest at 'https://humane-like-developer-edition.ap4.force.com/services/apexrest/SessionHuman' from origin 'chrome-extension://dgbedclgdamcknolmpacbbigocadoiko' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is my code
var HttpClient=function()
{
this.get=function(aUrl,aCallback)
{
var anHttpRequest=new XMLHttpRequest();
anHttpRequest.onreadystatechange=function()
{
if(anHttpRequest.readyState==4 && anHttpRequest.status==200)
{
aCallback(anHttpRequest.responseText);
}
}
anHttpRequest.open("GET",aUrl,true);
anHttpRequest.send(null);
}
}
var theurl='https://humane-like-developer-edition.ap4.force.com/services/apexrest/SessionHuman';
var client=new HttpClient();
client.get(theurl,function(response){
alert(response);

No 'Access-Control-Allow-Origin' header is present on the requested resource.
The requested resource must respond an Access-Control-Allowed-Origin header matching your Origin request header.
If it is a public API you should respond with *.
Note: Protocol is type of the response if it is not *, multiple values are not allowed, as well as wildcards are not allowed.

Related

Svelte (not SvelteKit) Add CORS "allow origin ..." in client's HTTP Header

So I keep having the error:
Access to fetch at 'http://localhost:8000/<...>' from origin 'http://localhost:8080' 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.
I would like to know how to add the field Access-Control-Allow-Originin the HTTP Header for a Svelte website. I precise it again, I am on Svelte, not on SvelteKit (Foud lots of solution for SvelteKit)
I would have think it could be added in the main.ts but I get an error if I do so :
const app = new App({
target: document.body,
props: {
name: 'my APP'
},
headers: {
'Access-Control-Allow-Origin': '*' // or, e.g. replacing * by http://localhost:8000
}
});
And I get the error:
Argument of type '{ target: HTMLElement; props: { name: string; }; headers: { 'Access-Control-Allow-Origin': string; }; }' is not assignable to parameter of type 'Svelte2TsxComponentConstructorParameters<any>'.
Object literal may only specify known properties, and 'headers' does not exist in type 'Svelte2TsxComponentConstructorParameters<any>'.ts(2345)
So, where can I set that ? 😅
NB. I also found this about CORS with NodeJS, can I use it with Svelte, or it will not work ?
CORS has nothing to do with Svelte; the server has to allow access from another origin, not the client. So whatever is serving http://localhost:8000 has to set the headers. How exactly that is done depends on the type of server.
The example that can be downloaded from the REPL uses sirv-cli to preview the compiled Svelte files. To make Sirv return requests with CORS headers, the flag -c can be used which just needs to be added to the start script in package.json.
{
...
"scripts": {
...
"start": "sirv public --no-clear -c"
},
}

fetch(url, {method:HEAD}) gives CORS error only if file doesn't exist

I need to check if a list of files is present on a server. When running this code
const promises = sentences.map(sentence => {
return fetch(`https://.../${sentence.id}.mp3`, {
method: 'HEAD',
cache: 'no-store',
})
})
const responses = await Promise.all(promises)
const notFound = responses.filter(response => !response.ok)
And having set the .htaccess file in the directory to
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET "
The response status for a file that exists is 200, but for the files that doesn't exist there's still the CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource. which prevents the function to finish.
Is this due to the 404 "Not Found - The requested URL was not found on this server." redirection? How can I prevent this?
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET "
To set these headers on non-200 responses (ie. 404s), you need to use the always condition. For example:
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Methods: "GET "
Reference:
https://httpd.apache.org/docs/current/mod/mod_headers.html#header

How can I tell Fluid FrameWork Tinylicious to allow cross-origin request from a specific URL?

I am hoping to use Tinylicious/Fluid Framework to enable communication across clients that are on different machines. For app-specific purposes, I have my app server running over https (at https://<domain1>.ngrok.io/). I then have Tinylicious serving from a different https URL (at https://<domain2>.ngrok.io/). Here is how I'm instantiating my Fluid client and connection (code adapted from https://github.com/microsoft/FluidHelloWorld):
import { ContainerSchema, SharedMap } from "#fluid-experimental/fluid-framework";
import { FrsClient, FrsConnectionConfig, FrsContainerConfig, InsecureTokenProvider } from "#fluid-experimental/frs-client";
import { getContainerId } from "./utils";
const { id, isNew } = getContainerId();
const localConfig: FrsConnectionConfig = {
tenantId: "local",
tokenProvider: new InsecureTokenProvider("anyValue", { id: "userId" }),
orderer: "https://<domain2>.ngrok.io",
storage: "https://<domain2>.ngrok.io"
};
const client = new FrsClient(localConfig);
const containerConfig: FrsContainerConfig = { id };
const containerSchema: ContainerSchema = {
name: "hello-world-demo-container",
initialObjects: { data: SharedMap }
};
const { fluidContainer } = isNew
? await client.createContainer(containerConfig, containerSchema)
: await client.getContainer(containerConfig, containerSchema);
...
However, when I run my app I get this cross-origin error when trying to connect to Tinylicious, because my app (at https://<domain1>.ngrok.io/) has a different domain than Tinylicious (https://<domain2>.ngrok.io/):
Access to XMLHttpRequest at 'https://<domain2>.ngrok.io/documents/local' from origin 'https://<domain1>.ngrok.io' 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.
Is there a way I can instantiate Tinylicious or another Fluid service and tell it origins (i.e., https://<domain1>.ngrok.io/) it should allow?
This is because there is no Access-Control-Allow-Origin header from the ngrok origin page.
Because you're just running this for local testing, you can use a plugin that adds the Access-Control-Allow-Origin header to every request. This Chrome extension does that for you, although I'm sure there are others.
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en

Reactjs App request.get

I have a react js app which does a simple http get. It does not use webpack and use package.json
var request = require('request');
var options = {
url: 'http://localhost:8181/api/v1/status',
headers: {
'Access-Control-Allow-Origin':'*'
}
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);
This code is getting failed and I am getting the following error
localhost/:1 Failed to load http://localhost:8181/api/v1/status: 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 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The server which I am trying to access is running python and I am already appending necessary header to make the request.
I am quite new to reactjs
How to fix this issue?
Let's breakdown the error message. The first part:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Means your Python server did not set an Access-Control-Allow-Origin header. You should make sure your python server sets this header in the response. If that didn't work, continue:
The response had HTTP status code 405.
HTTP Status Code 405 means method not allowed. Your python server may also need to set the header: Access-Control-Allow-Methods: <method>, <method>. So in include each one you want to allow, such as GET, POST, OPTIONS.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

Missing Access-Control-Allow-Origin header

I have a local mobile services running at localhost. I try to call the service from a webpage running in the same solution, but on a different port.
The calling code looks like this.
var MobileServiceClient = WindowsAzure.MobileServiceClient;
var client = new MobileServiceClient('http://localhost:62541/', xxxxxxxxxxxxxxxx);
var table = client.getTable("todoitem");
$(document).ready(function () {
$("#b").click(function () {
table.read().done(function (result) {
$("#t").text(JSON.stringify(result));
},
function (err) {
alert("Error: " + err);
});
And my controller in my mobile service looks like this.
[EnableCors(origins: "*", headers: "*", methods: "*")]
[RequiresAuthorization(AuthorizationLevel.Anonymous)]
public class TodoItemController : TableController<TodoItem>
I get the following error when calling my service using the code above.
XMLHttpRequest cannot load http://localhost:62541/tables/todoitem. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:60111' is therefore not allowed access.
How can I supply the missing 'Access-Control-Allow-Origin' header from my service?

Resources