I'm trying to use the Wikidata API, but all I'm getting is:
Fetch API cannot load https://www.wikidata.org/w/api.php?action=wbsearchentities&search=Ingmar%20Bergman&language=en&limit=20&format=json&origin=http%3A%2F%2Fwww.dev.example.com%3A3000. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.dev.example.com:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is the code:
const headers = new Headers();
const origin = "http://www.dev.example.com:3000";
headers.append("Origin", origin);
headers.append("Content-Type", "application/json; charset=UTF-8");
const url = "https://www.wikidata.org/w/api.php";
const query = {
action: "wbsearchentities",
search: "Ingmar Bergman",
language: "en",
limit: 20,
format: "json",
origin
};
const myInit = new Request(url + "?" + qs.stringify(query), {
method: "GET",
mode: "cors-with-forced-preflight",
headers
});
fetch(myInit)
.then(function(res) {
console.log(res);
})
.catch(function(err){
console.log(err);
});
I have tried JSONP as well, no success. Running the link in the browser (just without the origin parameter) gives a proper response.
So why do you add the "origin" parameter at all? Just leave it off, or add "&callback=some_function" to get JSONP.
add origin=* to the querystring, e.g.
https://www.wikidata.org/w/api.php?action=wbsearchentities&language=es&type=item&format=json&origin=*&search=Agav
Related
Using the Nextjs getServerSideProps function I make a fetch request to my API. My API checks origin headers for CORS but gets the origin header as undefined. Why is this happening and is there a way around this?
I get origin headers while making fetch requests normally from the browser in Next. This issue only occurs when the request is made to the API via the server from Nextjs getServerSideProps.
What I did was adding the Origin parameter to the header object in the fetch request and adding the url from the .env file to easily change it for production.
//Create fetch's options
const options = {
mode: 'cors',
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Origin: `${process.env.NEXT_PUBLIC_FRONT_URL}`,
},
};
//Fetch data from the API
const res = await fetch('changeForYouURL', options);
I am trying to set up an AWS lambda function, however when I call the endpoint, I am getting this error message back in the console.
Access to fetch at 'https://*.execute-api.eu-west-1.amazonaws.com/default/' from origin 'http://localhost:3000' 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 have set the CORS policy on the AWS Gateway
Here is my request code... I am just trying to print out the body of the response for testing purposes.
const response = await fetch(
'https://**********.execute-api.eu-west-1.amazonaws.com/default/**************',
{
method: 'POST',
body: "{'test': 'test'}",
headers: {
'X-Api-Key': '*****************************',
},
}
);
const text: any = await response.text();
console.log(text);
Weirdly when I look in fiddler, it is sending the OPTIONS and also returning a correct response, which is currently just printing out the different headers passed to the function.
If you've lambda proxy integration enabled you'll have to add headers from lambda.
From AWS documentation CORS section
For a Lambda proxy integration or HTTP proxy integration, you can still set up the required OPTIONS response headers in API Gateway. However, your backend is responsible for returning the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers, because a proxy integration doesn't return an integration response.
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "https://www.example.com",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
you can read more here
I am building a simple REST API using ktor and used cors but when i send a simple get request with no headers data the server works fine but if i want the client to have say key:1 the server doesn`t respond me correctly, it says the problem is
Failed to load http://127.0.0.1:8080/test: Response to preflight request doesn't pass access control check: 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 403.
so here is my ktor code
install(ContentNegotiation) {
gson {
}
}
install(ForwardedHeaderSupport)
install(DefaultHeaders)
install(CORS)
{
method(HttpMethod.Options)
method(HttpMethod.Get)
method(HttpMethod.Post)
method(HttpMethod.Put)
method(HttpMethod.Delete)
method(HttpMethod.Patch)
header(HttpHeaders.AccessControlAllowHeaders)
header(HttpHeaders.ContentType)
header(HttpHeaders.AccessControlAllowOrigin)
allowCredentials = true
anyHost()
maxAge = Duration.ofDays(1)
}
...
get("test"){
val a = call.request.headers["key"]
println(a)
call.respond(Product(name = a))
}
and my javascript code looks like this....
fetch('http://shop-ix.uz:8080/test', {
headers: {
"key": "1"
})
.then(response => response.json())
.then(json => {
console.log(json);
})
please help me
You need to whitelist your headers like this:
install(CORS) {
header("key")
}
This needs to be done with every custom HTTP header you intend to use.
Make sure all the headers and required methods should be allowed during Ktor CORS installation. I was facing the same issue, then I realized that I didn't add allowHeader(HttpHeaders.AccessControlAllowOrigin)
Although in the request header it was present. Because of that I am getting forbidden error (403)!
My Request Header!
Axios({
method: 'GET',
url: 'http://127.0.0.1:8080/connect',
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
params: {
...
}
})
Allowing CORS
install(CORS) {
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Post)
allowMethod(HttpMethod.Get)
allowHeader(HttpHeaders.AccessControlAllowOrigin)
allowHeader(HttpHeaders.ContentType)
anyHost()
}
Check that what your request header wants is allowed on the server during CORS.
install(CORS) {
exposeHeader("key")
}
difference between header and exposeHeader - first allow to make call with this header, but second allow to use it on client side
I'm trying to get linkedIn oauth2 access token but I stuck on making last request to https://www.linkedin.com/oauth/v2/accessToken
const body = new URLSearchParams([
['grant_type', 'authorization_code'],
['code', code],
['redirect_uri', 'http://localhost:3000/'],
['client_id', CLIENT_ID],
['client_secret', CLIENT_SECRET]
]);
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});
window.fetch('https://www.linkedin.com/oauth/v2/accessToken', method: 'POST',body, headers)
.then(response => response.json())
.then(data => {
// rest of code
})
LinkedIn returns
Fetch API cannot load https: //www.linkedin.com/oauth/v2/accessToken. 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 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
so I tried to make request in 'no-cors' mode. I've got 200 but I can't get body of response,status is 0, body is null and response.json() throws SyntaxError: Unexpected end of input.
For anyone who came across this problem. We solved it by passing data from LinkedIn (code) to our backend. Backend have no need to send any preflight OPTIONS requests and can get access token without problem.
I found out your issue,
The Content-Type header value is not correct.
It's meant to be
const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
NOT
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});
DOCS: https://developer.linkedin.com/docs/oauth2 (Step 3)
I am trying to covert my jQuery ajax call to use isomorphic fetch instead
My jQuery ajax call looks like this:
$.ajax({
url: 'myURL',
dataType: "script",
cache: true,
success() {
notify();
}
});
and my isomorphic fetch looks like this:
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/javascript');
fetch('myURL', {
headers: myHeaders,
mode: 'cors',
cache: 'default'
}).then(function(){
notify();
}).catch(function(error) {
console.log('request failed', error)
})
In the isomorphic-fetch version I am getting a CORS error in the browser:
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8080' is therefore not allowed access. The response had HTTP status code 501. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
However, the ajax call works fine.
What am I doing wrong?