No 'Access-Control-Allow-Origin' when using XMLHttpRequest - xmlhttprequest

Following this documentation of Codeship API: https://apidocs.codeship.com/v2/projects/update-project
I am trying to use XMLHttpRequest to fetch the data. The code is generated from the documentation, so I am assuming it should work.
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.codeship.com/v2/organizations/uuidhere/projects?type=basic");
console.log('good');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
console.log('ok');
xhr.setRequestHeader("authorization", token here);
xhr.send(data);
console.log(data)
However, when I test it in my localhost, it gives me
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.
It's weird that it still happens after putting
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
Please help

Related

Why is Axios sending an extra 204 preflight request with my POST request?

Whenever I send a POST request using Vue.js (3.x), an additional request to the same URL is being made with HTTP status code 204 & type of "preflight".
What is this preflight request and how can I fix it so it isn't sent as a duplicate?
Register.vue
async submit() {
this.button = true;
try {
const response = await axios.post(`register`, this.form);
if(response.data.success == false)
{
console.log(response.data.message);
}
else
{
this.$router.push('/');
}
}
catch (error)
{
let { errors } = error.response.data;
this.button = false;
this.errors = {};
Object.keys(errors).forEach(element => {
this.errors[element] = errors[element][0];
});
}
},
This is not an issue and is controlled by the browser by design.
It is not something Axios or any other HTTP client decides to send.
A preflight request is a CORS OPTIONS request & are automatically sent by browsers specifically to check if the server would support the call you are trying to make in terms of method, headers and origin.
You can safely ignore the requests if they do not fail as that means that the server will not be rejecting your request on the basis of the aforementioned factors.
Your issue relates to the endpoint not existing as you are getting a 404 Not Found error - check to see if the endpoint exists or if you are calling it correctly.

CouchDB authentication ,CORS issue

I get this error when trying to authenticate :
Access to fetch at 'http://localhost:5984/r/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
This is my code:
var rdb = new PouchDB('localhost:5984/r',
{ fetch: function (url, opts) {
opts.headers.set('X-Auth-CouchDB-Roles', '_admin');
return PouchDB.fetch(url, opts);
}
});

Response to preflight request doesn't pass access control No 'Access-Control-Allow-Origin'

I have a Vue.js application that uses axios to send request to ApiGee Server.
This is the code i use to send request to APIgee.
const headers = {
'X-API-Key': 'randomKey123123'
}
return axios({
method: 'get',
url: url,
headers: headers
}).then(response => {
console.log(response)
})
from the ApiGee, I can see OPTIONS request being received first since I done the request from the client side browser.
I can also see the X-API-Key header key but the value is missing.
The error I'm getting from the browser console is
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Below code helped me you can try this format:
created() {
// POST request using axios with set headers
const article = { title: "Vue POST Request Example" };
const headers = {
'X-API-Key': 'randomKey123123'
};
axios.post(url, article, { headers })
.then(response => console.log(response.data)
);
}

How to GET json data from API with a header

I'm trying to get JSON data from an API using NodeJS and Express, but it requires a header I'm not sure how to input the header into the get request.
The documentation says:
curl -H"X-FullContact-APIKey:$your_key"
'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com'
How do I do a add a get request with a header? I looked everywhere on Stackoverflow for days, and havent found anything. Everything is for PHP, nothing for NodeJS w/ Express. How can I do this with the Request Node NPM Manager Package
Not sure on how your request code looks like, but this should do it; right?
var request = require('request');
var options = {
url: 'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com',
headers: {
'X-FullContact-APIKey': '$your_key'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
console.log(result);
}
}
request(options, callback);

CORS doesn't work

i was trying to make asynchronous call to Yahoo's symbol suggest JSONP API, so there's cross domain problem, I have read this document and try to change it's url , the following are the codes i use
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
// var url = 'http://updates.html5rocks.com';
var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
but the problem still not solved:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
does anyone know why? Also, I compared the code in document with regular ajax code, they are almost the same, how does CORS work?
thanks
For CORS to work, the server needs to set the Access-Control-Allow-Origin header. If you do not control the server, and the server hasn't set that header, then I'm afraid you're out of luck.
CORS replaces JSONP as the way to load cross-domain json content, but with JSONP the server also needs to implement it.
If the owner of the content doesn't want you to use it, the browser will reject it.
Edit: of course you can avoid the cross-browser issue by having your server get the content from the original server, and having the browser get it from your own server. More work, but it's not cross-browser anymore.