CouchDB authentication ,CORS issue - authentication

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

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.

Companies House(UK) get request, axios

I want to access data from Companies House
I have an account
I createad an app
I get an API key
On JavaScript domains I have my URL.
When I try to do a request I get a CORS ERROR, and I am not sure why.
axios
.get(this.$companiesHouseUrl, {
params: {
q: this.search_for_company
},
crossDomain: true,
headers: {
Authorization: "Basic " + btoa(this.$companiesHouseKey + ":")
}
})
.then(response => {
console.log("Response:", response);
})
.catch(e => {
console.log("Error:", e);
});
On there forum I found this article, but still..
Access to XMLHttpRequest at 'https://api.companieshouse.gov.uk/?q=as'
from origin 'http://URL' 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.

Browser Cancels PUT requests

I've got a rails api and a react front end with axios to interact with the api. Have enabled CORS in rails, but the below request gets cancelled by the browser and can't find the reason for it.
Request copied as "fetch" call:
fetch("http://localhost:3000/api/v1/profile",
{
"credentials":"include",
"headers":{
"accept":"application/json, text/plain, */*",
"accept-language":"en-GB,en-US;q=0.9,en;q=0.8",
"authorization":"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwic2NwIjoiYWNjb3VudCIsImF1ZCI6bnVsbCwiaWF0IjoxNTg2OTY4MjIwLCJleHAiOjE1ODcwNTQ2MjAsImp0aSI6IjhkNTE2YjIzLTA1MGQtNGU2MS04ZWE1LWM3ZGIwMzkxNTg0NCJ9.KuwtVNB5minrOs3lvfNjt7lVQSWNRXdqZsbErb6SrGM",
"content-type":"application/json",
"sec-fetch-dest":"empty",
"sec-fetch-mode":"cors",
"sec-fetch-site":"same-site"
},
"referrer":"http://localhost:3001/profile?",
"referrerPolicy":"no-referrer-when-downgrade",
"body":"{\"first_name\":\"testsdasd\",\"last_name\":\"asadeesdfsfs\"}",
"method":"PUT",
"mode":"cors"
});
Is this getting cancelled due to CORS? BTW other post requests are getting through.
Thanks a lot.
Below is the code using axios.
async updateProfileData(profile) {
try {
let axiosResponse = await AxiosClient.instance().put('http://localhost:3000/api/v1/profile', {
first_name: profile.first_name,
last_name: profile.last_name
},{
headers: {
"Content-Type": "application/json"
}
});
return axiosResponse;
} catch (e) {
return e.response;
}
}
Found the answer.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://localhost:3000/api/v1/profile’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).
https://developer.mozilla.org/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default

No 'Access-Control-Allow-Origin' when using 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

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});