Create POST Request using JS - javascript

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);
});

Related

Access to fetch at 'https://myurl' from origin 'null' has been blocked by CORS policy:

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

How to fix cors error faced even with cors setup on the backend

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!

Getting error to make an API Post Call using simple HTML

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

API call working through server side code (node.js, php) but not through JS in browser using fetch()

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

Unable to fetch POST without no-cors in header

On making request like that:
return fetch(
'http://localhost:8000/login',
{ method: 'POST',
headers: new Headers(
{"Content-Type": "application/json",
"Accept":"application/json"}
),
body: JSON.stringify(
{'name': 'Tom', 'password': 'Soyer'}
)
}
).then( response => { console.log(response);})
.catch(err => console.log(err))
request running with method OPTIONS instead POST.
Only on adding mode: 'no-cors' request become POST:
return fetch(
'http://localhost:8000/login',
{ method: 'POST',
mode: 'no-cors',
headers: new Headers(
{"Content-Type": "application/json",
"Accept":"application/json"}
),
body: JSON.stringify(
{'name': 'Tom', 'password': 'Soyer'}
)
}
).then( response => { console.log(response);})
.catch(err => console.log(err))
but response not ok than (even if network response status is 200): {type: "opaque", url: "", status: 0, ok: false, statusText: ""…}
I suppose it because
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded multipart/form-data text/plain
described here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Is any way bring to live POST json data with fetch?
The custom Content-Type header you're sending causes your request to be preflighted, which means an OPTIONS request, containing some metadata about the POST request that is about to be dispatched, will be sent before the actual POST request.
Your server needs to be prepared to deal with this OPTIONS request. You haven't specified what the server is written in, but with express for example, you can register a middleware that intercepts all 'OPTIONS' requests, sets the Access-Control-Allow-Origin: * and Access-Control-Allow-Headers: Content-Type headers, and responds with 200.
If it is possible for you to make the request using a 'Content-Type': 'text/plain' header, that would solve your problem. Alternatively you could use something that bypasses XHR entirely, like JSONP.
When using non-cors, all headers must be valid simple-headers. The only valid values for the content-type header that qualifies as a simple-header is:
headers: [
['Content-Type', 'application/x-www-form-urlencoded'],
['Content-Type', 'multipart/form-data'],
['Content-Type', 'text/plain'],
]
Exceptions with contingencies:
headers: [
['Content-Type', 'application/csp-report'],
['Content-Type', 'application/expect-ct-report+json'],
['Content-Type', 'application/xss-auditor-report'],
['Content-Type', 'application/ocsp-request'],
]
simple-header
cors-protocol-exceptions
If you are trying to call an api and getting stuck with this in your react app you can add a proxy to the server and the cors error will get removed
just add this line at the package.json
"proxy":"url-to-your-server",

Categories

Resources