Without adding mode as 'no-cors':
Error : APICALL.html:1 Access to fetch at 'http://url' from origin 'null' 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 added mode as 'no-cors' but then i get another error of Bad Request.
Error : APICALL.html:66 POST http://url net::ERR_ABORTED 400 (Bad Request)
Code :
var data = {
Name: "Test",
Category: "Test-Category",
Mobile: "999999999999",
Email: "test#gmail.com",
Question: "Test Question",
};
var options = {
method: "POST",
mode: "no-cors",
origin: "*",
cache: "no-store",
headers: {
"Cache-Control": "no-store",
"Content-Type": "application/json",
},
body: data,
};
fetch("http://url", options)
.then((data) => {
if (!data.ok) {
throw Error(data.status);
}
return data.json();
})
.then((update) => {
console.log(update);
})
.catch((e) => {
console.log(e);
});
Chinese: 因为存在跨域情况,需要后端服务器开启跨域,允许你访问。
English: The server is not enabled to allow this port to cross domains because of cross domain conditions
Related
Im using javascript to send a Post request to Jira and and it display this error on the console browser "Access to fetch at 'https://myurl' from origin 'null' 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."
here is the my code
var myHeaders = new Headers();
myHeaders.append(
"Authorization",
"Basic ************************************************************************"
);
myHeaders.append("Content-Type", "application/json");
myHeaders.append(
"Cookie",
"atlassian.xsrf.token=********************************************************",
);
var raw = JSON.stringify({
serviceDeskId: "99",
requestTypeId: "9999",
requestFieldValues: {
summary: "test",
description: "test",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch(
"https://myurl",
requestOptions
)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error)); // console display : "error TypeError: //Failed to fetch"
when i add to header ==> mode: "no-cors"
it display this error ==> net::ERR_ABORTED 415
i tried also to add
mode: "cors",
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
and it display ==> error TypeError: Failed to fetch
I want to send a POST request to my backend from my website. But I get following error:
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.
My Code
const response = await fetch("http://172.18.6.249:8090/test", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: `{
"Id": 78912,
"Customer": "Jason Sweet",
"Quantity": 1,
"Price": 18.00
}`,
});
response.json().then(data => {
console.log(data);
});
The server doesn't use any kind of authentication at the moment.
How can I avoid the error?
CORS policy is very important and part of security.
In your case if you want to ignore CORS then you may use this : mode : "no-cors" in fetch Api
If this problem still persists then this CORS policy are registered on your backend. So, you are not able to hit request from your IP address.
below is front-end code example :
const response = await fetch("http://172.18.6.249:8090/test", {
method: 'POST',
mode : "no-cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: `{
"Id": 78912,
"Customer": "Jason Sweet",
"Quantity": 1,
"Price": 18.00
}`,
});
response.json().then(data => {
console.log(data);
});
I have configured my code in this manner on my express backend and have the cors library installed.
I am however getting this error:
Access to fetch at 'mybackend.com' from origin 'domain1.com' 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.
How can I solve this?
My backend and frontend code are as below respectively
const allowedDomains = [
'domain 1',
'domain 2',
];
app.use(cors(
{
origin: function (origin, callback) {
if (allowedDomains.indexOf(origin) != -1) {
callback(null, true);
} else {
callback(new Error(`Access has been blocked `));
}
},
credentials: true,
}
));
await fetch(`mybackend.com' ,{
method:'GET',
headers: new Headers({
'Content-Type':'application/json',
'Authorization':`Bearer ${token}`,
}),
body:null,
})
As per my limited understanding of Fetch API and CORS, I think you have to add mode: 'cors' as well as the header Access-Control-Allow-Origin: '*' or Access-Control-Allow-Origin: 'mybackend.com'. After doing that, your await fetch(...) block would look something like this.
fetch(URL, {
mode: 'cors',
method:'GET',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type':'application/json',
'Authorization':`Bearer ${token}`,
},
body:null,
})
.then(response => response.json())
.then(data => { ... });
Hope this helps!
My API has following CORS setup:
(I am the owner, I can change these settings)
Middleware function:
// HeaderMiddleware ...
func HeaderMiddleware(next httprouter.Handle) httprouter.Handle {
return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-APIKEY")
// ! Production
// if r.Header.Get("X-APIKEY") != "fdfdsf5df6d541cd6" || r.RemoteAddr != frontendURL {
// w.WriteHeader(http.StatusForbidden)
// json.NewEncoder(w).Encode(NoContentResponse{Success: false, Error: "You aren't allowed to request the api here."})
// return
// }
// ! Production
next(w, r, p)
})
}
The X-APIKEY header is not necessary yet, a request without it just works fine:
fetch('http://localhost:8013/tobi#gmx.at/usage', { headers: { } })
.then(response => response.json())
.then(console.log)
returns {used: false} (expected response)
However, if I add the X-APIKEY header:
fetch('http://localhost:8013/tobi#gmx.at/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } })
.then(response => response.json())
.then(console.log)
following error is thrown:
Access to fetch at 'http://localhost:8013/tobiwibu#gmx.at/usage' from origin 'http://localhost:8080' 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.
If I do the request with the X-APIKEY header in Postman, it says that the Access-Control-Allow-Origin header is sent along:
P.S.: I already tried other headers, it works!
If I do the request with chrome (without X-APIKEY header), the Access-Control-Allow-Origin header is sent.
Thanks for your help!
I've now fixed it like this:
I misuse the http Accept header for my API-Token.
Example:
fetch('http://10.0.0.11:8013/lopm#htl/usage',
{"headers":{ "Accept": "fdfdsf5df6d541cd6++" }})
.then(response => response.json())
.then(console.log)
Of course, this isn't a really nice solution, but it does its job.
Thanks for all of you for giving me helpful tips!
I am trying to make an API POST request via fetch(). When I execute it server side ( PHP or Node.js ) it works properly. When trying to execute it in the browser I get two errors:
1) 405 Error - Method not allowed
2) Access to fetch at 'url' from origin 'null' 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 tried adding: mode: "no-cors". I then get the following error:
"401 Unauthorized"
with the following response:
401 response
Here is my standard js setup:
const TrailData = {
email: "test#test.com",
first_name: "sample string 5",
last_name: "sample string 6",
phone2: "12121212"
};
// TRAIL POST ( NOT WORKING )
fetch('http://webapi.mymarketing.co.il/api/contacts', {
method: "POST",
mode: 'no-cors',
headers: {
"Authorization": "API CODE //here comes the API CODE",
"Content-Type": "application/json"
},
body: JSON.stringify(TrailData)
})
.then(res => console.log(res) )
.then(data => console.log(data))
.catch(err => console.log(err))
My Node js setup is:
var postData = {
sms_status: "None",
email: "test#test.com",
first_name: "sample string 5",
last_name: "sample string 6",
};
let axiosConfig = {
headers: {
"Authorization": "API CODE",
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
const Trail = async () =>{
try {
const response = await axios.post('http://webapi.mymarketing.co.il/api/contacts', postData, axiosConfig)
console.log(response)
} catch (error) {
throw new Error(error)
}
}
Trail()
Node JS works. I get a 200 OK response. The first one doesnt!
Is it possible that the API blocks requests made from the browser?
I have tried so many ways and failed every time using the browser.
Thank you for any help!
you can't send extra headers without CORS (Authorization header)
because server does not respond to preflight request you are not allowed to send that request
without CORS you are allowed to send only "Simple requests" see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
and https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
for more information